认识框架:scrapy
以前的爬虫,我们所使用的是只是简单的在Python编译器下的爬取,现在,我们要使用一个简单易用的框架来实现我们的功能,今天主要讲解的是scrapy框架
认识一下:
scrapy是为了爬取网站上的结构性的数据而设计的运用框架,假如你没有得到这个网站的API和通过程序获取信息外,那么scrapy可以帮助你
创建第一个爬虫:
准备:系统(Ubuntu16.04) 编译环境:pycharm
实现的功能:爬取部分的网站,比如:京东 唯品会 糯米
新建一个scrapy 项目:scrapy startproject newproject
显示如下则为创建成功
创建好的结构:
程序代码如下:
items.py:
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.item import Item, Field class NewprojectItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() url = scrapy.Field() title =scrapy.Field() link =scrapy.Field() pass
详细的讲解:
Item 是保存爬取到的数据的容器;其使用方法和python字典类似, 并且提供了额外保护机制来避免拼写错误导致的未定义字段错误。
类似在ORM中做的一样,您可以通过创建一个 scrapy.Item
类, 并且定义类型为 scrapy.Field
的类属性来定义一个Item。 (如果不了解ORM, 不用担心,您会发现这个步骤非常简单)
首先根据需要从dmoz.org获取到的数据对item进行建模。 我们需要从dmoz中获取名字,url,以及网站的描述。 对此,在item中定义相应的字段。编辑 tutorial
目录中的 items.py
文件:
sittings.py
# -*- coding: utf-8 -*- # Scrapy settings for newproject project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'newproject' SPIDER_MODULES = ['newproject.spiders'] NEWSPIDER_MODULE = 'newproject.spiders'pipelines.py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class NewprojectPipeline(object): def process_item(self, item, spider): return item
dmoz_spider.py
from scrapy.spider import Spider class DmozSpider(Spider): name = "dmoz" allowed_domains = ["peihua.cn"] start_urls = [ "http://www.peihua.cn/zhaosheng/default.aspx", "http://www.peihua.cn/library/default.aspx" ] def parse(self, response): filename = response.url.split("/")[-2] open(filename, 'wb').write(response.body)
详细的讲解:
name:必须的是唯一的,您不可以为不同的的spider设置相同的名字
allowed_domains:允许的域名,这个是你的爬虫爬取的时候需要的总网站
start_urls:包含了了爬虫爬取所需要的不同的URL列表,这个可以是一个也可以是多个,因此第一个被获取的页面将是其中的一个,后续的URL则是从URL获取到的数据中提取
parse():这个是spider的一个方法,被调用时候,每个初始URL完成下载后生成的response对象将会作为唯一的参数传递给该函数。该方法负责解析返回的数据(相应的数据 response data),提取数据以及生成需要下一步处理的request 对象。
特别注意的是:这里面涉及到的知识点有很多,比如:def () 正则表达式 spilt() with ... as ...: 但是不要紧,这部分的知识点在我的博客中都是有的
那么这样的话就可以爬去得到你想要的这个了,如果你显示的是以下的,那么你就成功了
还有你在你的文件(newproject)下面可以看到以下的这些
最后祝您爬取的更加的牛逼,谢谢观看