Scrapy 是用 Python 实现的一个为了爬取网站数据、提取结构性数据而编写的应用框架。html
Scrapy 常应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。mysql
一般咱们能够很简单的经过 Scrapy 框架实现一个爬虫,抓取指定网站的内容或图片。redis
Scrapy Engine(引擎): 负责Spider、ItemPipeline、Downloader、Scheduler中间的通信,信号、数据传递等。sql
Scheduler(调度器): 它负责接受引擎发送过来的Request请求,并按照必定的方式进行整理排列,入队,当引擎须要时,交还给引擎(主要功能url去重,构建url队列)。数据库
Downloader(下载器):负责下载Scrapy Engine(引擎)发送的全部Requests请求,并将其获取到的Responses交还给Scrapy Engine(引擎),由引擎交给Spider来处理,json
Spider(爬虫):它负责处理全部Responses,从中分析提取数据,获取Item字段须要的数据,并将须要跟进的URL提交给引擎,再次进入Scheduler(调度器).缓存
Item Pipeline(管道):它负责处理Spider中获取到的Item,并进行进行后期处理(详细分析、过滤、存储等)的地方。架构
Downloader Middlewares(下载中间件):你能够看成是一个能够自定义扩展下载功能的组件。app
Spider Middlewares(Spider中间件):你能够理解为是一个能够自定扩展和操做引擎和Spider中间通讯的功能组件(好比进入Spider的Responses;和从Spider出去的Requests)框架
代码写好,程序开始运行...
1 引擎:Hi!Spider, 你要处理哪个网站? 2 Spider:老大要我处理xxxx.com。 3 引擎:你把第一个须要处理的URL给我吧。 4 Spider:给你,第一个URL是xxxxxxx.com。 5 引擎:Hi!调度器,我这有request请求你帮我排序入队一下。 6 调度器:好的,正在处理你等一下。 7 引擎:Hi!调度器,把你处理好的request请求给我。 8 调度器:给你,这是我处理好的request 9 引擎:Hi!下载器,你按照老大的下载中间件的设置帮我下载一下这个request请求 10 下载器:好的!给你,这是下载好的东西。(若是失败:sorry,这个request下载失败了。而后引擎告诉调度器,这个request下载失败了,你记录一下,咱们待会儿再下载) 11 引擎:Hi!Spider,这是下载好的东西,而且已经按照老大的下载中间件处理过了,你本身处理一下(注意!这儿responses默认是交给def parse()这个函数处理的) 12 Spider:(处理完毕数据以后对于须要跟进的URL),Hi!引擎,我这里有两个结果,这个是我须要跟进的URL,还有这个是我获取到的Item数据。 13 引擎:Hi !管道 我这儿有个item你帮我处理一下!调度器!这是须要跟进URL你帮我处理下。而后从第四步开始循环,直到获取完老大须要所有信息。 14 管道``调度器:好的,如今就作!
注意!只有当调度器中不存在任何request了,整个程序才会中止,(也就是说,对于下载失败的URL,Scrapy也会从新下载。)
#新建项目 :新建一个新的爬虫项目 scrapy startproject proName #建立爬虫文件 scrapy genspider spiName "www.xxx.com" #明确目标 (编写items.py):明确你想要抓取的目标 #编写爬虫文件:制做爬虫开始爬取网页 #存储内容 (pipelines.py):设计管道存储爬取内容
a. pip3 install wheel b. pip3 install Twisted-17.0.1-cp35-cp35m-win_amd64.whl c. pip3 install pywin32 d. pip3 install scrapy
scrapy startproject mySpider
其中, mySpider 为项目名称,能够看到将会建立一个 mySpider 文件夹,目录结构大体以下:
下面来简单介绍一下各个主要文件的做用:
mySpider/ scrapy.cfg mySpider/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py ...
这些文件分别是:
咱们打算抓取 http://www.itcast.cn/channel/teacher.shtml 网站里的全部讲师的姓名、职称和我的信息。
打开 mySpider 目录下的 items.py。
Item 定义结构化数据字段,用来保存爬取到的数据,有点像 Python 中的 dict,可是提供了一些额外的保护减小错误。
能够经过建立一个 scrapy.Item 类, 而且定义类型为 scrapy.Field 的类属性来定义一个 Item(能够理解成相似于 ORM 的映射关系)。
接下来,建立一个 ItcastItem 类,和构建 item 模型(model)。
import scrapy class ItcastItem(scrapy.Item): name = scrapy.Field() title = scrapy.Field() info = scrapy.Field()
1. 爬数据
在当前目录下输入命令,将在mySpider/spider目录下建立一个名为itcast的爬虫,并指定爬取域的范围:
scrapy genspider itcast "itcast.cn"
打开 mySpider/spider目录里的 itcast.py,默认增长了下列代码:
import scrapy class ItcastSpider(scrapy.Spider): name = "itcast" allowed_domains = ["itcast.cn"] start_urls = ( 'http://www.itcast.cn/', ) def parse(self, response): pass
其实也能够由咱们自行建立itcast.py并编写上面的代码,只不过使用命令能够免去编写固定代码的麻烦
要创建一个Spider, 你必须用scrapy.Spider类建立一个子类,并肯定了三个强制的属性 和 一个方法。
name = "" :这个爬虫的识别名称,必须是惟一的,在不一样的爬虫必须定义不一样的名字。
allow_domains = [ ] 是搜索的域名范围,也就是爬虫的约束区域,规定爬虫只爬取这个域名下的网页,不存在的URL会被忽略。
start_urls = () :爬取的URL元祖/列表。爬虫从这里开始抓取数据,因此,第一次下载的数据将会从这些urls开始。其余子URL将会从这些起始URL中继承性生成。
parse(self, response) :解析的方法,每一个初始URL完成下载后将被调用,调用的时候传入从每个URL传回的Response对象来做为惟一参数,主要做用以下:
负责解析返回的网页数据(response.body),提取结构化数据(生成item)
生成须要下一页的URL请求。
将start_urls的值修改成须要爬取的第一个url
start_urls = ("http://www.itcast.cn/channel/teacher.shtml",)
二、取数据,修改parse()方法
from mySpider.items import ItcastItem def parse(self, response): #open("teacher.html","wb").write(response.body).close() # 存放老师信息的集合 items = [] for each in response.xpath("//div[@class='li_txt']"): # 将咱们获得的数据封装到一个 `ItcastItem` 对象 item = ItcastItem() #extract()方法返回的都是unicode字符串 name = each.xpath("h3/text()").extract() title = each.xpath("h4/text()").extract() info = each.xpath("p/text()").extract() #xpath返回的是包含一个元素的列表 item['name'] = name[0] item['title'] = title[0] item['info'] = info[0] items.append(item) # 直接返回最后数据 return items
咱们暂时先不处理管道,此时保存数据能够在终端输入命令,指定-o参数
scrapy保存信息的最简单的方法主要有四种,-o 输出指定格式的文件,命令以下:
scrapy crawl itcast -o teachers.json #json格式,默认为Unicode编码 scrapy crawl itcast -o teachers.jsonlines #json lines格式,默认为Unicode编码 scrapy crawl itcast -o teachers.csv #csv 逗号表达式,可用Excel打开 scrapy crawl itcast -o teachers.xml #xml格式
若是将return改为yield,以下所示,yield会将item数据经过引擎提交给管道进行数据的存储
from mySpider.items import ItcastItem def parse(self, response): #open("teacher.html","wb").write(response.body).close() # 存放老师信息的集合 #items = [] for each in response.xpath("//div[@class='li_txt']"): # 将咱们获得的数据封装到一个 `ItcastItem` 对象 item = ItcastItem() #extract()方法返回的都是unicode字符串 name = each.xpath("h3/text()").extract() title = each.xpath("h4/text()").extract() info = each.xpath("p/text()").extract() #xpath返回的是包含一个元素的列表 item['name'] = name[0] item['title'] = title[0] item['info'] = info[0] #items.append(item) #将获取的数据交给pipelines yield item
此时pipelines.py文件编写以下:
import pymysql import redis class MyspiderPipeline(object): fp = None def open_spider(self,spider): #此方法只执行一次,在爬虫文件开始被执行时触发此方法 print("开始爬虫...") self.fp = open('./info.txt','w',encoding='utf-8') def process_item(self, item, spider): print("打印item",item) self.fp.write(item["name"]+':'+item["title"]+':'+item["info"]+'\n') return item #return的做用是将item交由下一个管道进行相应方式的存储 def close_spider(self,spider): #此方法只执行一次,在爬虫文件执行结束时触发此方法 print('结束爬虫...') self.fp.close() #将爬虫数据存储在mtsql数据库中 class MysqlPipeline(object): conn = None cursor = None def open_spider(self,spider): self.conn = pymysql.Connect(host="127.0.0.1",port=3306,user="root",password="12345",db="scrapy",charset="utf8") def process_item(self,item,spider): self.cursor = self.conn.cursor() try: sql = "insert into teachers(name,title,info) values (%s,%s,%s)" self.cursor.execute(sql,[item["name"],item["title"],item["info"]]) self.conn.commit() return item except Exception as e: self.conn.rollback() def close_spider(self,spider): self.conn.close() self.cursor.close() # 将爬虫文件缓存在redis数据库中 class RedisPipeline(object): conn = None def open_spider(self, spider): pool = redis.ConnectionPool(host='127.0.0.1',port=6379,db=5) self.conn = redis.Redis(connection_pool=pool) def process_item(self,item,spider): self.conn.lpush('teachersInfo',item) return item
利用管道进行存储时,注意不要忘了对settings.py文件进行相应的配置
ITEM_PIPELINES = { 'mySpider.pipelines.MyspiderPipeline': 300, #数字越小,优先级越高 'mySpider.pipelines.MysqlPipeline': 301, 'mySpider.pipelines.RedisPipeline': 302, }