Scrapy框架
- 官网链接:点击
- Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速、简单、可扩展的方式从网站中提取所需的数据。
- 但目前Scrapy的用途十分广泛,可用于如数据挖掘、监测和自动化测试等领域,也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。
- Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架。因此Scrapy使用了一种非阻塞(又名异步)的代码来实现并发。
一、框架安装和基础使用
1、安装
- linux mac os:
- pip install scrapy
- win:
- pip install wheel
- 下载twisted:https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
- pip install 下载好的框架.whl
- pip install pywin32
- pip install scrapy
2、基础使用
- 创建一个工程:scrapy startproject工程名称
- 在工程目录下创建一个爬虫文件:
- cd 工程
- scrapy genspider 爬虫文件的名称 起始url (例如:scrapy genspider qiubai www.qiushibaike.com)
- 对应的文件中编写爬虫程序来完成爬虫的相关操作
- 设置修改settings.py配置文件相关配置:
- 19行:USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' #伪装请求载体身份
- 22行:ROBOTSTXT_OBEY = False #可以忽略或者不遵守robots协议
- 执行爬虫程序:scrapy crawl 应用名称
- scrapy crawl 爬虫名称 :该种执行形式会显示执行的日志信息
- scrapy crawl 爬虫名称 --nolog:该种执行形式不会显示执行的日志信息


""" 目录结构: project_name/ scrapy.cfg: project_name/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py scrapy.cfg 项目的主配置信息。(真正爬虫相关的配置信息在settings.py文件中) items.py 设置数据存储模板,用于结构化数据,如:Django的Model pipelines 数据持久化处理 settings.py 配置文件,如:递归的层数、并发数,延迟下载等 spiders 爬虫目录,如:创建文件,编写爬虫解析规则 """ #spiders/qiubai.py import scrapy class QiubaiSpider(scrapy.Spider): # 爬虫文件的名称:通过爬虫文件的名称可以指定的定位到某一个具体的爬虫文件 name = 'qiubai' #允许的域名:只可以爬取指定域名下的页面数据(如果遇到非该域名的url则爬取不到数据) #一般不用直接注释了 #allowed_domains = ['https://www.qiushibaike.com/'] #起始url:当前工程将要爬取的页面所对应的url start_urls = ['https://www.qiushibaike.com/'] # 解析方法:访问起始URL并获取结果后的回调函数 # 该函数的response参数就是向起始的url发送请求后,获取的响应对象 # parse方法的返回值必须为可迭代对象或者NUll def parse(self, response): print(response.text) #获取字符串类型的响应内容 print(response.body)#获取字节类型的相应内容 # 建议大家使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # xpath为response中的方法,可以将xpath表达式直接作用于该函数中 odiv = response.xpath('//div[@id="content-left"]/div') content_list = [] # 用于存储解析到的数据 for div in odiv: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法可以将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] # xpath函数返回的为列表,列表中存放的数据为Selector类型的数据。 # 我们解析到的内容被封装在了Selector对象中,需要调用extract()函数将解析的内容从Selecor中取出。 author = div.xpath('.//div[@class="author clearfix"]/a/h2/text()')[0].extract() content = div.xpath('.//div[@class="content"]/span/text()')[0].extract() # author = div.xpath('./div/a[2]/h2/text()').extract_first() # content = div.xpath('.//div[@class="content"]/span/text()').extract_first() # 将解析到的内容封装到字典中 dic = { '作者': author, '内容': content } # 将数据存储到content_list这个列表中 content_list.append(dic) return content_list """ settings.py 19行 22行 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False
二、持久化存储
- 磁盘文件:
- 基于终端指令:
- 保证parse方法返回一个可迭代类型的对象(存储解析到的页面内容)
- 使用终端指令完成数据存储到制定磁盘文件中的操作
- scrapy crawl 爬虫文件名称–o 磁盘文件.后缀
- scrapy crawl qiubai -o qiubai.csv --nolog
- scrapy crawl qiubai -o qiubai.json --nolog
- scrapy crawl qiubai -o qiubai.xml --nolog
- 基于管道:
- items:数据结构模板文件,定义数据属性,存储解析到的页面数据
- pipelines:管道文件,接收数据(items),处理持久化存储的相关操作
- 代码实现流程:
- 爬虫文件爬取到数据后,需要将数据存储到items对象中。
- 使用yield关键字将items对象提交给pipelines管道文件进行持久化处理
- 在管道文件中的process_item方法中接收爬虫文件提交过来的item对象,然后编写持久化存储的代码将item对象中存储的数据进行持久化存储
- settings.py配置文件中开启管道
- 基于终端指令:
- 数据库:
- mysql
- redis
- 编码流程:
- 将解析到的页面数据存储到items对象
- 使用yield关键字将items提交给管道文件进行处理
- *****在管道文件中编写代码完成数据存储的操作【】
- 在配置文件中开启管道操作


""" 基于终端指令 1.保证parse方法返回一个可迭代类型的对象(存储解析到的页面内容) 2.使用终端指令完成数据存储到制定磁盘文件中的操作 scrapy crawl qiubai -o qiubai.csv --nolog """ # -*- coding: utf-8 -*- import scrapy class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议大家使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和作者 div_list = response.xpath('//div[@id="content-left"]/div') #存储解析到的页面数据 data_list = [] for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法可以将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() dict = { 'author':author, 'content':content } data_list.append(dict) return data_list """ settings.py 19行 22行 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False


""" 基于管道 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操作 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' # allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): # 建议大家使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和作者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: # xpath解析到的指定内容被存储到了Selector对象 # extract()该方法可以将Selector对象中存储的数据值拿到 # author = div.xpath('./div/a[2]/h2/text()').extract()[0] # extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() # 1.将解析到的数据值(author和content)存储到items对象 item = QiubaiproItem() item['author'] = author item['content'] = content # 2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class QiubaiproPipeline(object): fp = None # # 构造方法 # def __init__(self): # self.fp = None # 定义一个文件描述符属性 # 整个爬虫过程中,该方法只会在开始爬虫的时候被调用一次 def open_spider(self, spider): print('开始爬虫') self.fp = open('./qiubai_pipe.txt', 'w', encoding='utf-8') # 该方法就可以接受爬虫文件中提交过来的item对象,并且对item对象中存储的页面数据进行持久化存储 # 参数:item表示的就是接收到的item对象 # 每当爬虫文件向管道提交一次item,则该方法就会被执行一次 # 因为该方法会被执行调用多次,所以文件的开启和关闭操作写在了另外两个只会各自执行一次的方法中。 def process_item(self, item, spider): # print('process_item 被调用!!!') # 取出item对象中存储的数据值 author = item['author'] content = item['content'] # 持久化存储 self.fp.write(author + ":" + content + '\n\n\n') return item # 该方法只会在爬虫结束的时候被调用一次 def close_spider(self, spider): print('爬虫结束') self.fp.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent # USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproPipeline': 300, # 300表示为优先级,值越小优先级越高 }


""" 基于mysql的管道存储 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操作 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议大家使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和作者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法可以将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #1.将解析到的数据值(author和content)存储到items对象 #创建items对象 item = QiubaiproItem() item['author'] = author item['content'] = content #2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysql class QiubaiproPipelineByMysql(object): conn = None cursor = None def open_spider(self,spider): print('开始爬虫') #链接数据库 self.conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='123456',db='qiubai') #编写向数据库中存储数据的相关代码 def process_item(self, item, spider): #1.链接数据库 #2.执行sql语句 sql = 'insert into qiubai values("%s","%s")'%(item['author'],item['content']) self.cursor = self.conn.cursor() try: self.cursor.execute(sql) self.conn.commit() except Exception as e: print(e) self.conn.rollback() #3.提交事务 return item def close_spider(self,spider): print('爬虫结束') self.cursor.close() self.conn.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproPipelineByMysql': 300, #300表示为优先级,值越小优先级越高 }


""" 基于redis的管道存储 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操作 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议大家使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和作者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法可以将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #1.将解析到的数据值(author和content)存储到items对象 #创建items对象 item = QiubaiproItem() item['author'] = author item['content'] = content #2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import redis class QiubaiproPipelineByRedis(object): conn = None def open_spider(self,spider): print('开始爬虫') self.conn = redis.Redis(host='127.0.0.1',port=6379) def process_item(self, item, spider): dict = { 'author':item['author'], 'content':item['content'] } # 写入redis中 self.conn.lpush('data', dict) return item """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproPipelineByRedis': 300, #300表示为优先级,值越小优先级越高 }


""" 不同形式的持久化操作 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操作 scrapy crawl qiubai --nolog 3.主要就是管道文件pipelines.py和配置文件settings.py -需要在管道文件中编写对应平台的管道类 -在配置文件中对自定义的管道类进行生效操作 """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议大家使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和作者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法可以将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #1.将解析到的数据值(author和content)存储到items对象 #创建items对象 item = QiubaiproItem() item['author'] = author item['content'] = content #2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import redis class QiubaiproByRedis(object): conn = None def open_spider(self,spider): print('开始爬虫') self.conn = redis.Redis(host='127.0.0.1',port=6379) def process_item(self, item, spider): dict = { 'author':item['author'], 'content':item['content'] } # 写入redis中 self.conn.lpush('data', dict) return item class QiubaiproPipeline(object): fp = None # 整个爬虫过程中,该方法只会在开始爬虫的时候被调用一次 def open_spider(self, spider): print('开始爬虫') self.fp = open('./qiubai_pipe.txt', 'w', encoding='utf-8') # 该方法就可以接受爬虫文件中提交过来的item对象,并且对item对象中存储的页面数据进行持久化存储 # 参数:item表示的就是接收到的item对象 # 每当爬虫文件向管道提交一次item,则该方法就会被执行一次 # 因为该方法会被执行调用多次,所以文件的开启和关闭操作写在了另外两个只会各自执行一次的方法中。 def process_item(self, item, spider): # print('process_item 被调用!!!') # 取出item对象中存储的数据值 author = item['author'] content = item['content'] # 持久化存储 self.fp.write(author + ":" + content + '\n\n\n') return item # 该方法只会在爬虫结束的时候被调用一次 def close_spider(self, spider): print('爬虫结束') self.fp.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False #下列结构为字典,字典中的键值表示的是即将被启用执行的管道文件和其执行的优先级。 ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproByRedis': 300, #300表示为优先级,值越小优先级越高 'qiubaiPro.pipelines.QiubaiproPipeline': 200, } #上述代码中,字典中的两组键值分别表示会执行管道文件中对应的两个管道类中的process_item方法,实现两种不同形式的持久化操作。


""" 多个url页面数据爬取 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操作 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiByPages.items import QiubaibypagesItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] #设计一个通用的url模板 url = 'https://www.qiushibaike.com/text/page/%d/' pageNum = 1 def parse(self, response): div_list = response.xpath('//*[@id="content-left"]/div') for div in div_list: author = div.xpath('./div[@class="author clearfix"]/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #创建一个items对象,将解析到数据值存储到items对象中 item = QiubaibypagesItem() item['author'] = author item['content'] = content #将item提交给管道 yield item #请求的手动发送 #13表示的是最后一页的页码 if self.pageNum <= 13: print('爬取到了第%d页的页面数据'%self.pageNum) self.pageNum += 1 new_url = format(self.url % self.pageNum) #callback:将请求获取到的页面数据进行解析 yield scrapy.Request(url=new_url,callback=self.parse) """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaibypagesItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class QiubaibypagesPipeline(object): fp = None def open_spider(self,spider): print('开始爬虫') self.fp = open('./qiubai.txt','w',encoding='utf-8') def process_item(self, item, spider): self.fp.write(item['author']+":"+item['content']) return item def close_spider(self,spider): self.fp.close() print('爬虫结束') """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiByPages.pipelines.QiubaibypagesPipeline': 300, }
1、Scrapy核心组件
- 引擎(Scrapy):
- 用来处理整个系统的数据流处理, 触发事务(框架核心)
- 调度器(Scheduler):
- 用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL(抓取网页的网址或者说是链接)的优先队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址
- 下载器(Downloader):
- 用于下载网页内容,并将网页内容返回给蜘蛛(Scrapy下载器是建立在twisted这个高效的异步模型上的)
- 爬虫(Spiders):
- 爬虫是主要干活的, 用于从特定的网页中提取自己需要的信息, 即所谓的实体(Item)。用户也可以从中提取出链接,让Scrapy继续抓取下一个页面
- 项目管道(Pipeline):
- 负责处理爬虫从网页中抽取的实体,主要的功能是持久化实体、验证实体的有效性、清除不需要的信息。当页面被爬虫解析后,将被发送到项目管道,并经过几个特定的次序处理数据。
三、代理和cookie
1、post请求发送
- 问题:在之前代码中,我们从来没有手动的对start_urls列表中存储的起始url进行过请求的发送,但是起始url的确是进行了请求的发送,那这是如何实现的呢?
- 解答:其实是因为爬虫文件中的爬虫类继承到了Spider父类中的start_requests(self)这个方法,该方法就可以对start_urls列表中的url发起请求
- 【注意】start_requests方法默认的实现,是对起始的url发起get请求,如果想发起post请求,则需要子类重写该方法。


""" post请求发送 """ # -*- coding: utf-8 -*- import scrapy #需求:百度翻译中指定词条对应的翻译结果进行获取 class PostdemoSpider(scrapy.Spider): name = 'postDemo' #allowed_domains = ['www.baidu.com'] start_urls = ['https://fanyi.baidu.com/sug'] #该方法其实是父类中的一个方法:该方法可以对star_urls列表中的元素进行get请求的发送 #发起post: #1.将Request方法中method参数赋值成post #2.FormRequest()可以发起post请求(推荐) def start_requests(self): print('start_requests()') #post请求的参数 data = { 'kw': 'dog', } for url in self.start_urls: #formdata:请求参数对应的字典 yield scrapy.FormRequest(url=url,formdata=data,callback=self.parse) #发起get: # def start_requests(self): # for u in self.start_urls: # yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): print(response.text)
2、cookie
- 登录后,获取该用户个人主页这个二级页面的页面数据


""" cookie:豆瓣网个人登录,获取该用户个人主页这个二级页面的页面数据。 """ # -*- coding: utf-8 -*- import scrapy class DoubanSpider(scrapy.Spider): name = 'douban' #allowed_domains = ['www.douban.com'] start_urls = ['https://www.douban.com/accounts/login'] #重写start_requests方法 def start_requests(self): #将请求参数封装到字典 data = { 'source': 'index_nav', 'form_email': '15027900535', 'form_password': 'bobo@15027900535' } for url in self.start_urls: yield scrapy.FormRequest(url=url,formdata=data,callback=self.parse) #针对个人主页页面数据进行解析操作 def parseBySecondPage(self,response): fp = open('second.html', 'w', encoding='utf-8') fp.write(response.text) #可以对当前用户的个人主页页面数据进行指定解析操作 def parse(self, response): #登录成功后的页面数据进行存储 fp = open('main.html','w',encoding='utf-8') fp.write(response.text) #获取当前用户的个人主页 url = 'https://www.douban.com/people/185687620/' yield scrapy.Request(url=url,callback=self.parseBySecondPage)
3、代理
- 下载中间件作用:拦截请求,可以将请求的ip进行更换
- 流程:下载中间件类的自制定
- 配置文件中进行下载中间件的开启


""" 代理: 下载中间件作用:拦截请求,可以将请求的ip进行更换。 流程: 1. 下载中间件类的自制定 a) object b) 重写process_request(self,request,spider)的方法 2. 配置文件中进行下载中间件的开启。 """ # -*- coding: utf-8 -*- import scrapy class ProxydemoSpider(scrapy.Spider): name = 'proxyDemo' #allowed_domains = ['www.baidu.com/s?wd=ip'] start_urls = ['https://www.baidu.com/s?wd=ip'] def parse(self, response): fp = open('proxy.html','w',encoding='utf-8') fp.write(response.text) """ middlewares.py """ # -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals #自定义一个下载中间件的类,在类中事先process_request(处理中间价拦截到的请求)方法 class MyProxy(object): def process_request(self,request,spider): #请求ip的更换 request.meta['proxy'] = "https://178.128.90.1:8080" """ settings.py 19行 22行 56行 开启下载中间件 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False DOWNLOADER_MIDDLEWARES = { 'proxyPro.middlewares.MyProxy': 543, }
四、日志等级和请求传参
1、日志信息
- 日志等级(种类):
- ERROR:错误
- WARNING:警告
- INFO:一般信息
- DEBUG:调试信息(默认)
- 指定输入某一种日志信息:
- settings.py文件中配置:LOG_LEVEL ='ERROR'
- 将日志信息存储到指定文件中,而并非显示在终端里:
- settings.py文件中配置:LOG_FILE ='log.txt'
2、请求传参
- 爬取的数据值不在同一个页面中。
- 列表页和详情页的爬取


""" 请求传参 """ # -*- coding: utf-8 -*- import scrapy from moviePro.items import MovieproItem class MovieSpider(scrapy.Spider): name = 'movie' #allowed_domains = ['www.id97.com'] start_urls = ['http://www.id97.com/movie'] #专门用于解析二级子页面中的数据值 def parseBySecondPage(self,response): actor = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[1]/td[2]/a/text()').extract_first() language = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[6]/td[2]/text()').extract_first() longTime = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[8]/td[2]/text()').extract_first() #取出Request方法的meta参数传递过来的字典(response.meta) item = response.meta['item'] item['actor'] = actor item['language'] = language item['longTime'] = longTime #将item提交给管道 yield item def parse(self, response): #名称,类型,导演,语言,片长 div_list = response.xpath('/html/body/div[1]/div[1]/div[2]/div') for div in div_list: name = div.xpath('.//div[@class="meta"]/h1/a/text()').extract_first() #如下xpath方法返回的是一个列表,切列表元素为4 kind = div.xpath('.//div[@class="otherinfo"]//text()').extract() #将kind列表转化成字符串 kind = "".join(kind) url = div.xpath('.//div[@class="meta"]/h1/a/@href').extract_first() print(kind) #创建items对象 item = MovieproItem() item['name'] = name item['kind'] = kind #问题:如何将剩下的电影详情数据存储到item对象(meta) #需要对url发起请求,获取页面数据,进行指定数据解析 #meta参数只可以赋值一个字典(将item对象先封装到字典) yield scrapy.Request(url=url,callback=self.parseBySecondPage,meta={'item':item}) """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class MovieproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() name = scrapy.Field() kind = scrapy.Field() actor = scrapy.Field() language = scrapy.Field() longTime = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class MovieproPipeline(object): fp = None def open_spider(self,spider): self.fp = open('movie.txt','w',encoding='utf-8') def process_item(self, item, spider): detail = item['name']+':'+item['kind']+':'+item['actor']+':'+item['language']+':'+item['longTime']+'\n\n\n' self.fp.write(detail) return item def close_spider(self,spider): self.fp.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'moviePro.pipelines.MovieproPipeline': 300, }
五、CrawlSpider
- CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能。其中最显著的功能就是”LinkExtractors链接提取器“。Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适。
- 爬取全站方法1:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法)【手动请求的发送】。
- 爬取全站方法2:基于CrawlSpider的自动爬取进行实现(更加简洁和高效)。【推荐】
1、使用
- 创建scrapy工程:scrapy startproject projectName
- 创建爬虫文件:scrapy genspider -t crawl spiderName www.xxx.com (scrapy genspider -t crawl 爬虫名称 起始url)
- 此指令对比以前的指令多了 "-t crawl",表示创建的爬虫文件是基于CrawlSpider这个类的,而不再是Spider这个基类。
2、CrawlSpider整体爬取流程
- a):爬虫文件首先根据起始url,获取该url的网页内容
- b):链接提取器会根据指定提取规则将步骤a中网页内容中的链接进行提取
- c):规则解析器会根据指定解析规则将链接提取器中提取到的链接中的网页内容根据指定的规则进行解析
- d):将解析数据封装到item中,然后提交给管道进行持久化存储
- LinkExtractor:链接提取器。- 作用:提取response中符合规则的链接。
- Rule : 规则解析器。根据链接提取器中提取到的链接,根据指定规则提取解析器链接网页中的内容。
3、selenium在scrapy中的使用流程
- a):重写爬虫文件的构造方法,在该方法中使用selenium实例化一个浏览器对象(因为浏览器对象只需要被实例化一次)
- b):重写爬虫文件的closed(self,spider)方法,在其内部关闭浏览器对象。该方法是在爬虫结束时被调用
- c):重写下载中间件的process_response方法,让该方法对响应对象进行拦截,并篡改response中存储的页面数据
- d):在配置文件中开启下载中间件
- 原理分析: 当引擎将url对应的请求提交给下载器后,下载器进行网页数据的下载, 然后将下载到的页面数据,封装到response中,提交给引擎,引擎将response在转交给Spiders。 Spiders接受到的response对象中存储的页面数据里是没有动态加载的新闻数据的。 要想获取动态加载的新闻数据,则需要在下载中间件中对下载器提交给引擎的response响应对象进行拦截, 切对其内部存储的页面数据进行篡改,修改成携带了动态加载出的新闻数据, 然后将被篡改的response对象最终交给Spiders进行解析操作。
4、下载中间件(Downloader Middlewares)
- 下载中间件(Downloader Middlewares) 位于scrapy引擎和下载器之间的一层组件。
- 作用:引擎将请求传递给下载器过程中, 下载中间件可以对请求进行一系列处理。比如设置请求的 User-Agent,设置代理等
- 作用:在下载器完成将Response传递给引擎中,下载中间件可以对响应进行一系列处理。比如进行gzip解压等。
- 我们主要使用下载中间件处理请求,一般会对请求设置随机的User-Agent ,设置随机的代理。目的在于防止爬取网站的反爬虫策略。
5、UA池:User-Agent池
- 作用:尽可能多的将scrapy工程中的请求伪装成不同类型的浏览器身份。
- 操作流程:
- 在下载中间件中拦截请求
- 将拦截到的请求的请求头信息中的UA进行篡改伪装
- 在配置文件中开启下载中间件
6、代理池
- 作用:尽可能多的将scrapy工程中的请求的IP设置成不同的。
- 操作流程:
- 在下载中间件中拦截请求
- 将拦截到的请求的IP修改成某一代理IP
- 在配置文件中开启下载中间件


""" CrawlSpider LinkExtractor:顾名思义,链接提取器。 - 作用:提取response中符合规则的链接。 LinkExtractor( allow=r'Items/',# 满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。 deny=xxx, # 满足正则表达式的则不会被提取。 restrict_xpaths=xxx, # 满足xpath表达式的值会被提取 restrict_css=xxx, # 满足css表达式的值会被提取 deny_domains=xxx, # 不会被提取的链接的domains。 ) Rule : 规则解析器。根据链接提取器中提取到的链接,根据指定规则提取解析器链接网页中的内容。 Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True) - 参数介绍: 参数1:指定链接提取器 参数2:指定规则解析器解析数据的规则(回调函数) 参数3:是否将链接提取器继续作用到链接提取器提取出的链接网页中。当callback为None,参数3的默认值为true。 rules=( ):指定不同规则解析器。一个Rule对象表示一种提取规则。 """ # -*- coding: utf-8 -*- import scrapy #导入CrawlSpider相关模块 from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule #表示该爬虫程序是基于CrawlSpider类的 class ChoutiSpider(CrawlSpider): name = 'chouti' #allowed_domains = ['dig.chouti.com'] start_urls = ['https://dig.chouti.com/'] #链接提取器:用来提取指定的链接(url) #allow参数:赋值一个正则表达式 #链接提取器就可以根据正则表达式在页面中提取指定的链接 #提取到的链接会全部交给规则解析器 # 实例化了一个链接提取器对象,且指定其提取规则 link = LinkExtractor(allow=r'/all/hot/recent/\d+') #定义规则解析器,且指定解析规则通过callback回调函数 rules = ( #实例化了一个规则解析器对象 #规则解析器接受了链接提取器发送的链接后,就会对这些链接发起请求,获取链接对应的页面内容,就会根据指定的规则对页面内容中指定的数据值进行解析 #callback:指定一个解析规则(方法/函数) #follow:是否将链接提取器继续作用到连接提取器提取出的链接所表示的页面数据中 Rule(link, callback='parse_item', follow=True), ) #自定义规则解析器的解析规则函数 def parse_item(self, response): print(response) """ settings.py 19行 22行 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False


# -*- coding: utf-8 -*- import scrapy from newsPro.items import NewsproItem from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class Chinanews(CrawlSpider): name = 'chinanews' # allowed_domains = ['http://www.chinanews.com/scroll-news/news1.html'] #中国新闻网(滚动新闻) start_urls = ['http://www.chinanews.com/scroll-news/news1.html', 'http://finance.chinanews.com/cj/gd.shtml' ] custom_settings = { "ITEM_PIPELINES": {'newsPro.pipelines.NewsproPipeline': 300} } link = LinkExtractor(allow=r'http://www.chinanews.com/scroll-news/news\d+.html') link2 = LinkExtractor(allow=r'http://finance.chinanews.com/cj/gd.shtml') # 中国新闻网(财经新闻) rules = ( Rule(link, callback='parse_first', follow=True), Rule(link2, callback='parse_two', follow=True), ) n=0 def parse_first(self, response): li_list = response.xpath('/html/body//div[@class="content_list"]/ul/li') # print(len(li_list)) for li in li_list: url = li.xpath('./div[@class="dd_bt"]/a/@href').extract_first() url="http:%s"%url # print(url) yield scrapy.Request(url=url, callback=self.parse_con,) def parse_two(self, response): li_list = response.xpath('/html/body//div[@class="content_list"]/ul/li') # print(len(li_list)) for li in li_list: url = li.xpath('./div[@class="dd_bt"]/a/@href').extract_first() url="http://finance.chinanews.com%s"%url # print(url) yield scrapy.Request(url=url, callback=self.parse_con,) def parse_con(self, response): # self.n+=1 # print(self.n) # print(response) div= response.xpath('/html/body//div[@id="cont_1_1_2"]') title =div.xpath('./h1/text()').extract_first() ctime_s =div.xpath('//div[@class="left-t"]/text()').extract_first().split("来源:") editor =div.xpath('./div[@class="left_name"]/div[@class="left_name"]/text()').extract_first() source =ctime_s[-1] ctime = ctime_s[0] content_list =div.xpath('./div[@class="left_zw"]/p/text()').extract() content = "".join(content_list) # print('=======', title, '=======') # print('=======', ctime,'=======') # print('=======', source, '=======') # print('=======', editor, '=======') # print('=======',content, '=======') item = NewsproItem() item['title'] =title.strip() item['source'] =source.strip() item['content'] =content.strip() item['ctime'] =ctime.strip() item['editor'] =editor.strip() yield item
六、基于redis的分布式爬虫
1、分布式爬虫
- 概念:多台机器上可以执行同一个爬虫程序,实现网站数据的分布爬取。
- 原生的scrapy框架是否可以自己实现分布式?
- 不可以。
- 原因1:因为多台机器上部署的scrapy会各自拥有各自的调度器,这样就使得多台机器无法分配start_urls列表中的url。(多台机器无法共享同一个调度器)
- 原因2:多台机器爬取到的数据无法通过同一个管道对数据进行统一的数据持久出存储。(多台机器无法共享同一个管道)
- 安装scrapy-redis组件:
- pip install scrapy-redis
- scrapy-redis组件:
- scrapy-redis是基于scrapy框架开发出的一套组件,其作用就是可以让scrapy实现分布式爬虫。
- 使用scrapy-redis组件中封装好的调度器,将所有的url存储到该指定的调度器中,从而实现了多台机器的调度器共享。
- 使用scrapy-redis组件中封装好的管道,将每台机器爬取到的数据存储通过该管道存储到redis数据库中,从而实现了多台机器的管道共享。
2、基于RedisCrawlSpider分布式爬取的流程
- redis配置文件的配置:
- win:redis.windows.conf linux:redis.conf
- 注释该行:bind 127.0.0.1,表示可以让其他ip访问redis
- 将yes该为no:protected-mode no,表示可以让其他ip操作redis,关闭保护模式
- redis服务器的开启:
- 基于配置配置文件
- 爬虫文件【区别】:
- 创建scrapy工程后,创建基于crawlSpider的爬虫文件
- 导入RedisCrawlSpider类(from scrapy_redis.spiders import RedisCrawlSpider),然后将爬虫文件修改成基于该类的源文件(class QiubaiSpider(RedisCrawlSpider):)
- 将start_url修改成redis_key = 'qiubaispider' # 调度器队列的名称 表示跟start_urls含义是一样
- 管道文件:
- 在配置文件中进行相应配置:将管道配置成scrapy-redis集成的管道
- 在scrapy-redis组件中已经帮助我们封装好了一个专门用于连接存储redis数据库的管道(RedisPipeline),因此我们直接使用即可,无需自己编写管道文件。
- 调度器:
- 在配置文件中将调度器切换成scrapy-redis集成好的调度器
- 配置文件:
- 在settings.py中开启管道且将管道配置成scrapy-redis集成的管道。
- 在settings.py中将调度器切换成scrapy-redis集成好的调度器
- 该管道默认会连接且将数据存储到本机的redis服务中,如果想要连接存储到其他redis服务中需要在settings.py中进行配置
- 开启redis数据库的服务:
- redis-server 配置文件
- 执行爬虫程序:
- cd 到存放xxx.py的spiders目录
- scrapy runspider xxx.py
- redis客户端:
- 向调度器的队列中扔一个起始url (lpush 调度器队列的名称 “起始url”)lpush wangyi https://news.163.com
- ctrl + c 停止爬取
- keys * 查看
- lrange wangyi:items 0 -1 查看
3、基于RedisSpider的第二种形式的分布式爬虫(网易新闻)
- 其他配置和上面一样,只有爬虫文件不一样
- 爬虫文件【区别】:
- 创建scrapy工程后,创建基于Spider的爬虫文件
- 导入RedisSpider类(from scrapy_redis.spiders import RedisSpider),然后将爬虫文件修改成基于该类的源文件(class WangyiSpider(RedisSpider):)
- 将start_url修改成redis_key = 'wangyi' 调度器队列名称
4、UA池:
- 在中间件类中进行导包 from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
- 封装一个基于UserAgentMiddleware的类,且重写该类的process_requests方法
5、代理池:
- 注意请求url的协议后到底是http还是https
6、selenium如何被应用到scrapy:
- 在爬虫文件中导入webdriver类
- 在爬虫文件的爬虫类的构造方法中进行了浏览器实例化的操作
- 在爬虫类的closed方法中进行浏览器关闭的操作
- 在下载中间件的process_response方法中编写执行浏览器自动化的操作


""" redis实现分布式基本流程 """ # -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from redisPro.items import RedisproItem #导入scrapy-redis中的模块 from scrapy_redis.spiders import RedisCrawlSpider from redisPro.items import RedisproItem class QiubaiSpider(RedisCrawlSpider): name = 'qiubai' #allowed_domains = ['https://www.qiushibaike.com/pic/'] #start_urls = ['https://www.qiushibaike.com/pic/'] #调度器队列的名称 redis_key = 'qiubaispider' #表示跟start_urls含义是一样 #【注意】近期糗事百科更新了糗图板块的反爬机制,更新后该板块的页码链接/pic/page/2/s=5135066, # 末尾的数字每次页面刷新都会变化,因此正则不可写为/pic/page/\d+/s=5135066而应该修改成/pic/page/\d+ link = LinkExtractor(allow=r'/pic/page/\d+') rules = ( Rule(link, callback='parse_item', follow=True), ) def parse_item(self, response): #将图片的url进行解析 div_list = response.xpath('//*[@id="content-left"]/div') for div in div_list: img_url = div.xpath('./div[@class="thumb"]/a/img/@src').extract_first() item = RedisproItem() item['img_url'] = img_url yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class RedisproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() img_url = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class RedisproPipeline(object): def process_item(self, item, spider): return item """ settings.py 19行 22行 ...管道 ...调度器 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { #'redisPro.pipelines.RedisproPipeline': 300, 'scrapy_redis.pipelines.RedisPipeline': 400, } # 使用scrapy-redis组件的去重队列 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # 使用scrapy-redis组件自己的调度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # 是否允许暂停 SCHEDULER_PERSIST = True #如果redis服务器不在自己本机,则需要配置redis服务的ip和端口 REDIS_HOST = '172.20.10.7' #redis数据库所在的机器上的ip地址 REDIS_PORT = 6379 #REDIS_PARAMS = {‘password’:’123456’}


""" selenium在scrapy中的应用 from scrapy.http import HtmlResponse #参数介绍: #拦截到响应对象(下载器传递给Spider的响应对象) #request:响应对象对应的请求对象 #response:拦截到的响应对象 #spider:爬虫文件中对应的爬虫类的实例 def process_response(self, request, response, spider): #响应对象中存储页面数据的篡改 if request.url in['http://news.163.com/domestic/','http://news.163.com/world/','http://news.163.com/air/','http://war.163.com/']: spider.bro.get(url=request.url) js = 'window.scrollTo(0,document.body.scrollHeight)' spider.bro.execute_script(js) time.sleep(2) #一定要给与浏览器一定的缓冲加载数据的时间 #页面数据就是包含了动态加载出来的新闻数据对应的页面数据 page_text = spider.bro.page_source #篡改响应对象 return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding='utf-8',request=request) else: return response """ # -*- coding: utf-8 -*- import scrapy from selenium import webdriver from wangyiPro.items import WangyiproItem from scrapy_redis.spiders import RedisSpider class WangyiSpider(RedisSpider): name = 'wangyi' #allowed_domains = ['www.xxxx.com'] #start_urls = ['https://news.163.com'] redis_key = 'wangyi' def __init__(self): #实例化一个浏览器对象(实例化一次) self.bro = webdriver.Chrome(executable_path='/Users/bobo/Desktop/chromedriver') #必须在整个爬虫结束后,关闭浏览器 def closed(self,spider): print('爬虫结束') self.bro.quit() def parse(self, response): lis = response.xpath('//div[@class="ns_area list"]/ul/li') indexs = [3,4,6,7] li_list = [] #存储的就是国内,国际,军事,航空四个板块对应的li标签对象 for index in indexs: li_list.append(lis[index]) #获取四个板块中的链接和文字标题 for li in li_list: url = li.xpath('./a/@href').extract_first() title = li.xpath('./a/text()').extract_first() #print(url+":"+title) #对每一个板块对应的url发起请求,获取页面数据(标题,缩略图,关键字,发布时间,url) yield scrapy.Request(url=url,callback=self.parseSecond,meta={'title':title}) def parseSecond(self,response): div_list = response.xpath('//div[@class="data_row news_article clearfix "]') #print(len(div_list)) for div in div_list: head = div.xpath('.//div[@class="news_title"]/h3/a/text()').extract_first() url = div.xpath('.//div[@class="news_title"]/h3/a/@href').extract_first() imgUrl = div.xpath('./a/img/@src').extract_first() tag = div.xpath('.//div[@class="news_tag"]//text()').extract() tags = [] for t in tag: t = t.strip(' \n \t') tags.append(t) tag = "".join(tags) #获取meta传递过来的数据值title title = response.meta['title'] #实例化item对象,将解析到的数据值存储到item对象中 item = WangyiproItem() item['head'] = head item['url'] = url item['imgUrl'] = imgUrl item['tag'] = tag item['title'] = title #对url发起请求,获取对应页面中存储的新闻内容数据 yield scrapy.Request(url=url,callback=self.getContent,meta={'item':item}) #print(head+":"+url+":"+imgUrl+":"+tag) def getContent(self,response): #获取传递过来的item item = response.meta['item'] #解析当前页面中存储的新闻数据 content_list = response.xpath('//div[@class="post_text"]/p/text()').extract() content = "".join(content_list) item['content'] = content yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class WangyiproItem(scrapy.Item): # define the fields for your item here like: head = scrapy.Field() url = scrapy.Field() imgUrl = scrapy.Field() tag = scrapy.Field() title = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class WangyiproPipeline(object): def process_item(self, item, spider): print(item['title']+':'+item['content']) return item """ middlewares.py """ # -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals from scrapy.http import HtmlResponse import time from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware import random #UA池代码的编写(单独给UA池封装一个下载中间件的一个类) #1,导包UserAgentMiddlware类 class RandomUserAgent(UserAgentMiddleware): def process_request(self, request, spider): #从列表中随机抽选出一个ua值 ua = random.choice(user_agent_list) #ua值进行当前拦截到请求的ua的写入操作 request.headers.setdefault('User-Agent',ua) #批量对拦截到的请求进行ip更换 class Proxy(object): def process_request(self, request, spider): #对拦截到请求的url进行判断(协议头到底是http还是https) #request.url返回值:http://www.xxx.com h = request.url.split(':')[0] #请求的协议头 if h == 'https': ip = random.choice(PROXY_https) request.meta['proxy'] = 'https://'+ip else: ip = random.choice(PROXY_http) request.meta['proxy'] = 'http://' + ip class WangyiproDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None #拦截到响应对象(下载器传递给Spider的响应对象) #request:响应对象对应的请求对象 #response:拦截到的响应对象 #spider:爬虫文件中对应的爬虫类的实例 def process_response(self, request, response, spider): #响应对象中存储页面数据的篡改 if request.url in['http://news.163.com/domestic/','http://news.163.com/world/','http://news.163.com/air/','http://war.163.com/']: spider.bro.get(url=request.url) js = 'window.scrollTo(0,document.body.scrollHeight)' spider.bro.execute_script(js) time.sleep(2) #一定要给与浏览器一定的缓冲加载数据的时间 #页面数据就是包含了动态加载出来的新闻数据对应的页面数据 page_text = spider.bro.page_source #篡改响应对象 return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding='utf-8',request=request) else: return response PROXY_http = [ '153.180.102.104:80', '195.208.131.189:56055', ] PROXY_https = [ '120.83.49.90:9000', '95.189.112.214:35508', ] user_agent_list = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 " "(KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 " "(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 " "(KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 " "(KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 " "(KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 " "(KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 " "(KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 " "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 " "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24" ] """ settings.py 19行 22行 56开启下载中间件 ...管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False DOWNLOADER_MIDDLEWARES = { 'wangyiPro.middlewares.WangyiproDownloaderMiddleware': 543, 'wangyiPro.middlewares.RandomUserAgent': 542, 'wangyiPro.middlewares.Proxy': 541, } ITEM_PIPELINES = { #'wangyiPro.pipelines.WangyiproPipeline': 300, 'scrapy_redis.pipelines.RedisPipeline': 400, } #配置redis服务的ip和端口 REDIS_HOST = '172.20.10.7' #redis数据库所在的机器上的ip地址 REDIS_PORT = 6379 #REDIS_PARAMS = {‘password’:’123456’} # 使用scrapy-redis组件的去重队列 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # 使用scrapy-redis组件自己的调度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # 是否允许暂停 SCHEDULER_PERSIST = True


基于scrapy-redis的第二种形式的分布式爬虫: 基于RedisSpider实现的分布式爬虫(网易新闻) a) 代码修改(爬虫类): i. 导包:from scrapy_redis.spiders import RedisSpider ii. 将爬虫类的父类修改成RedisSpider iii. 将起始url列表注释,添加一个redis_key(调度器队列的名称)的属性 b) redis数据库配置文件的配置redisxxx.conf: i. #bind 127.0.0.1 ii. protected-mode no c) 对项目中settings进行配置: i. #配置redis服务的ip和端口 REDIS_HOST = 'redis服务的ip地址' REDIS_PORT = 6379 #REDIS_PARAMS = {‘password’:’123456’} ii. # 使用scrapy-redis组件的去重队列 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # 使用scrapy-redis组件自己的调度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # 是否允许暂停 SCHEDULER_PERSIST = True iii. 使用可以被共享的管道 ITEM_PIPELINES = { #'wangyiPro.pipelines.WangyiproPipeline': 300, 'scrapy_redis.pipelines.RedisPipeline': 400, } d) 开启redis数据库的服务:redis-server 配置文件 e) 执行爬虫文件:scrapy runspider wangyi.py f) 向调度器的队列中扔一个起始url: i. 开启redis客户端 ii. 向调度器队列中扔一个起始url Lpush wangyi https://news.163.com