scrapy框架的请求流程¶
scrapy框架?
Scrapy 是基于twisted框架开发而来,twisted是一个流行的事件驱动的python网络框架。因此Scrapy使用了一种非阻塞(又名异步)的代码来实现并发。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 1、引擎(EGINE) 引擎负责控制系统所有组件之间的数据流,并在某些动作发生时触发事件。有关详细信息,请参见上面的数据流部分。 2、调度器(SCHEDULER) 用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL的优先级队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址 3、下载器(DOWLOADER) 用于下载网页内容, 并将网页内容返回给EGINE,下载器是建立在twisted这个高效的异步模型上的 4、爬虫(SPIDERS) SPIDERS是开发人员自定义的类,用来解析responses,并且提取items,或者发送新的请求 5、项目管道(ITEM PIPLINES) 在items被提取后负责处理它们,主要包括清理、验证、持久化(比如存到数据库)等操作 下载器中间件(Downloader Middlewares)位于Scrapy引擎和下载器之间,主要用来处理从EGINE传到DOWLOADER的请求request,已经从DOWNLOADER传到EGINE的响应response, 6、爬虫中间件(Spider Middlewares) 位于EGINE和SPIDERS之间,主要工作是处理SPIDERS的输入(即responses)和输出(即requests) |
安装和创建: https://www.cnblogs.com/pyedu/p/10314215.html
scrapy框架+selenium的使用¶
1 使用情景:
在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值。但是通过观察我们会发现,通过浏览器进行url请求发送则会加载出对应的动态加载出的数据。那么如果我们想要在scrapy也获取动态加载出的数据,则必须使用selenium创建浏览器对象,然后通过该浏览器对象进行请求发送,获取动态加载的数据值
2 使用流程
1 重写爬虫文件的__init__()构造方法,在该方法中使用selenium实例化一个浏览器对象(因为浏览器对象只需要被实例化一次).
2 重写爬虫文件的closed(self,spider)方法,在其内部关闭浏览器对象,该方法是在爬虫结束时被调用.
3 重写下载中间件的process_response方法,让该方法对响应对象进行拦截,并篡改response中存储的页面数据.
4 在settings配置文件中开启下载中间件
3 使用案例: 爬取XXX网站新闻的部分板块内容
爬虫文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options # 使用无头浏览器
无头浏览器设置
chorme_options = Options()
chorme_options.add_argument("--headless")
chorme_options.add_argument("--disable-gpu")
class WangyiSpider(scrapy.Spider):
name = 'wangyi'
# allowed_domains = ['wangyi.com'] # 允许爬取的域名
start_urls = ['https://news.163.com/']
# 实例化一个浏览器对象
def __init__(self):
self.browser = webdriver.Chrome(chrome_options=chorme_options)
super().__init__()
def start_requests(self):
url = "https://news.163.com/"
response = scrapy.Request(url,callback=self.parse_index)
yield response
# 整个爬虫结束后关闭浏览器
def close(self,spider):
self.browser.quit()
# 访问主页的url, 拿到对应板块的response
def parse_index(self, response):
div_list = response.xpath("//div[@class='ns_area list']/ul/li/a/@href").extract()
index_list = [3,4,6,7]
for index in index_list:
response = scrapy.Request(div_list[index],callback=self.parse_detail)
yield response
# 对每一个板块进行详细访问并解析, 获取板块内的每条新闻的url
def parse_detail(self,response):
div_res = response.xpath("//div[@class='data_row news_article clearfix ']")
# print(len(div_res))
title = div_res.xpath(".//div[@class='news_title']/h3/a/text()").extract_first()
pic_url = div_res.xpath("./a/img/@src").extract_first()
detail_url = div_res.xpath("//div[@class='news_title']/h3/a/@href").extract_first()
infos = div_res.xpath(".//div[@class='news_tag//text()']").extract()
info_list = []
for info in infos:
info = info.strip()
info_list.append(info)
info_str = "".join(info_list)
item = WangyiproItem()
item["title"] = title
item["detail_url"] = detail_url
item["pic_url"] = pic_url
item["info_str"] = info_str
yield scrapy.Request(url=detail_url,callback=self.parse_content,meta={"item":item}) # 通过 参数meta 可以将item参数传递进 callback回调函数,再由 response.meta[...]取出来
# 对每条新闻的url进行访问, 并解析
def parse_content(self,response):
item = response.meta["item"] # 获取从response回调函数由meta传过来的 item 值
content_list = response.xpath("//div[@class='post_text']/p/text()").extract()
content = "".join(content_list)
item["content"] = content
yield item
|
下载中间件中篡改响应数据
需要导入 HtmlResponse类, 这个类是用来将响应数据包装成符合HTTP协议形式.
from scrapy.http import HtmlResponse
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class WangyiproDownloaderMiddleware(object):
# 可以拦截到request请求
def process_request(self, request, spider):
# 在进行url访问之前可以进行的操作, 更换UA请求头, 使用其他代理等
pass
# 可以拦截到response响应对象(拦截下载器传递给Spider的响应对象)
def process_response(self, request, response, spider):
"""
三个参数:
# request: 响应对象所对应的请求对象
# response: 拦截到的响应对象
# spider: 爬虫文件中对应的爬虫类 WangyiSpider 的实例对象, 可以通过这个参数拿到 WangyiSpider 中的一些属性或方法
"""
# 对页面响应体数据的篡改, 如果是每个模块的 url 请求, 则处理完数据并进行封装
if request.url in ["http://news.163.com/domestic/","http://war.163.com/","http://news.163.com/world/","http://news.163.com/air/"]:
spider.browser.get(url=request.url)
# more_btn = spider.browser.find_element_by_class_name("post_addmore") # 更多按钮
# print(more_btn)
js = "window.scrollTo(0,document.body.scrollHeight)"
spider.browser.execute_script(js)
# if more_btn and request.url == "http://news.163.com/domestic/":
# more_btn.click()
time.sleep(1) # 等待加载, 可以用显示等待来优化.
row_response= spider.browser.page_source
return HtmlResponse(url=spider.browser.current_url,body=row_response,encoding="utf8",request=request) # 参数url指当前浏览器访问的url(通过current_url方法获取), 在这里参数url也可以用request.url
# 参数body指要封装成符合HTTP协议的源数据, 后两个参数可有可无
else:
return response # 是原来的主页的响应对象
# 请求出错了的操作, 比如ip被封了,可以在这里设置ip代理
def process_exception(self, request, exception, spider):
print("添加代理开始")
ret_proxy = get_proxy()
request.meta["proxy"] = ret_proxy
print("为%s添加代理%s" %(request.url,ret_proxy), end="")
return None
# 其他方法无需动
|
中间件文件里设置UA池:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware
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"
]
class RandomUserAgent(UserAgentMiddleware): # 如何运行此中间件? settings 直接添加就OK
def process_request(self, request, spider):
ua = random.choice(user_agent_list)
# 在请求头里设置ua
request.headers.setdefault("User-Agent",ua)
|
settings配置文件中:
1 2 3 4 | DOWNLOADER_MIDDLEWARES = {
'WangYiPro.middlewares.WangyiproDownloaderMiddleware': 543,
'WangYiPro.middlewares.RandomUserAgent': 542,
}
|
scrapy结合selenium进行动态加载页面内容爬取¶
动态页面与静态页面¶
比较常见的页面形式可以分为两种:
- 静态页面
- 动态页面
使用requests进行数据获取的时候一般使用的是respond.text来获取网页源码,然后通过正则表达式提取出需要的内容。
例如:
1 2 3 | import requests response = requests.get('https://www.baidu.com') print(response.text.encode('raw_unicode_escape').decode()) |

百度源代码.png
但是动态页面使用上述操作后发现,获取到的内容与实际相差很大。
例如我们打开如下页面:
1 | https://www.aqistudy.cn/historydata/monthdata.php?city=北京 |
右键选择查看网页源代码

查看网页源代码.png
在网页源代码中查找页面中存在的一个数据:2014-02的PM10为155。

北京空气质量指数.png
这时打开F12查看Elements 可以看到155在元素中有显示

检查.png
综上基本可以明白静态页面和动态页面的区别了。
有两种方式可以获取动态页面的内容:
- 破解JS,实现动态渲染
- 使用浏览器模拟操作,等待模拟浏览器完成页面渲染
由于第一个比较困难所以选择方法二
需求分析¶
获取各个城市近年来每天的空气质量
- 日期
- 城市
- 空气质量指数
- 空气质量等级
- pm2.5
- pm10
- so2
- co
- no2
- o3
使用scrapy¶
scrapy操作的基本流程如下:
1 2 3 4 5 6 | 1.创建项目:scrapy startproject 项目名称 2.新建爬虫:scrapy genspider 爬虫文件名 爬虫基础域名 3.编写item 4.spider最后return item 5.在setting中修改pipeline配置 6.在对应pipeline中进行数据持久化操作 |
创建¶
打开命令行,输入scrapy startproject air_history ,创建一个名为air_history的scrapy项目
进入该文件夹,输入scrapy genspider area_spider "aqistudy.cn",可以发现在spiders文件夹下多了一个名为area_spider的py文件
文件目录结构大概如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | . ├── air_history │ ├── __init__.py │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── settings.cpython-36.pyc │ ├── settings.py │ └── spiders │ ├── area_spider.py │ ├── __init__.py │ └── __pycache__ │ └── __init__.cpython-36.pyc └── scrapy.cfg |
编写item¶
根据需求编写item如下,spider最后return item,把值传递给它
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import scrapy class AirHistoryItem(scrapy.Item): # define the fields for your item here like: data = scrapy.Field() #日期 city = scrapy.Field() #城市 aqi = scrapy.Field() #空气质量指数 level = scrapy.Field() #空气质量等级 pm2_5 = scrapy.Field() #pm2.5 pm10 = scrapy.Field() #pm10 so2 = scrapy.Field() #so2 co = scrapy.Field() #co no2 = scrapy.Field() #no2 o3 = scrapy.Field() #o3 |
编写爬虫¶
首先可以得知首页是https://www.aqistudy.cn/historydata/
所以将它赋值给一个名为base_url的变量,方便后续使用
自动创建的爬出中携带了爬虫的名字,这个name在启动爬虫的时候需要用到,现在暂时用不到
1 2 3 4 | name = 'area_spider' allowed_domains = ['aqistudy.cn'] # 爬取的域名,不会超出这个顶级域名 base_url = "https://www.aqistudy.cn/historydata/" start_urls = [base_url] |
城市信息¶
进入首页之后可以看到一大批的城市信息,所以我们第一步就是获取有哪些城市
1 2 3 4 5 6 | def parse(self, response): print('爬取城市信息....') url_list = response.xpath("//div[@class='all']/div[@class='bottom']/ul/div[2]/li/a/@href").extract() # 全部链接 city_list = response.xpath("//div[@class='all']/div[@class='bottom']/ul/div[2]/li/a/text()").extract() # 城市名称 for url, city in zip(url_list, city_list): yield scrapy.Request(url=url, callback=self.parse_month, meta={'city': city}) |
使用插件XPath Helper可以对xpath进行一个测试,看看定位的内容是否正确

xpath.png
随意点击一个地区可以发现url变为https://www.aqistudy.cn/historydata/monthdata.php?city=北京
所以url_list获取到的是需要进行拼接的内容monthdata.php?city=城市名称
city_list的最后部分是text()所以它拿到的是具体的文本信息
将获取到的url_list和city_list逐个传递给scrapy.Request其中url是需要继续爬取的页面地址,city是item中需要的内容,所以将item暂时存放在meta中传递给下个回调函数self.parse_month
月份信息¶
1 2 3 4 5 6 | def parse_month(self, response): print('爬取{}月份...'.format(response.meta['city'])) url_list = response.xpath('//tbody/tr/td/a/@href').extract() for url in url_list: url = self.base_url + url yield scrapy.Request(url=url, callback=self.parse_day, meta={'city': response.meta['city']}) |
此步操作获取了每个城市的全部月份信息,并拿到了每个月份的url地址。把上面传递下来的city继续向下传递
最终数据¶
获取到最终的URL之后,把item实例化,然后完善item字典并返回item
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def parse_day(self, response): print('爬取最终数据...') item = AirHistoryItem() node_list = response.xpath('//tr') node_list.pop(0) # 去除第一行标题栏 for node in node_list: item['data'] = node.xpath('./td[1]/text()').extract_first() item['city'] = response.meta['city'] item['aqi'] = node.xpath('./td[2]/text()').extract_first() item['level'] = node.xpath('./td[3]/text()').extract_first() item['pm2_5'] = node.xpath('./td[4]/text()').extract_first() item['pm10'] = node.xpath('./td[5]/text()').extract_first() item['so2'] = node.xpath('./td[6]/text()').extract_first() item['co'] = node.xpath('./td[7]/text()').extract_first() item['no2'] = node.xpath('./td[8]/text()').extract_first() item['o3'] = node.xpath('./td[9]/text()').extract_first() yield item |
使用中间件实现selenium操作¶
打开中间件文件middlewares.py
由于我是在服务器上进行爬取,所以我选择使用谷歌的无界面浏览器chrome-headless
1 2 3 4 5 6 7 8 9 | from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--headless') # 使用无头谷歌浏览器模式 chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') # 指定谷歌浏览器路径 webdriver.Chrome(chrome_options=chrome_options,executable_path='/root/zx/spider/driver/chromedriver') |
然后进行页面渲染后的源码获取
request.url是传递到中间件的url,由于首页是静态页面,所以首页不进行selenium操作
1 2 3 4 5 6 | if request.url != 'https://www.aqistudy.cn/historydata/': self.driver.get(request.url) time.sleep(1) html = self.driver.page_source self.driver.quit() return scrapy.http.HtmlResponse(url=request.url, body=html.encode('utf-8'), encoding='utf-8',request=request) |
后续的操作也很简单,最后将获取到的内容正确编码后返回给爬虫的下一步
middlewares全部代码¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | from scrapy import signals import scrapy from selenium import webdriver from selenium.webdriver.chrome.options import Options import time class AreaSpiderMiddleware(object): def process_request(self, request, spider): chrome_options = Options() chrome_options.add_argument('--headless') # 使用无头谷歌浏览器模式 chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') # 指定谷歌浏览器路径 self.driver = webdriver.Chrome(chrome_options=chrome_options,executable_path='/root/zx/spider/driver/chromedriver') if request.url != 'https://www.aqistudy.cn/historydata/': self.driver.get(request.url) time.sleep(1) html = self.driver.page_source self.driver.quit() return scrapy.http.HtmlResponse(url=request.url, body=html.encode('utf-8'), encoding='utf-8', request=request) |
使用下载器保存item内容¶
修改pipelines.py进行文件的存储
1 2 3 4 5 6 7 8 9 10 11 12 13 | import json class AirHistoryPipeline(object): def open_spider(self, spider): self.file = open('area.json', 'w') def process_item(self, item, spider): context = json.dumps(dict(item),ensure_ascii=False) + '\n' self.file.write(context) return item def close_spider(self,spider): self.file.close() |
修改settings文件使中间件,下载器生效¶
打开settings.py文件
修改以下内容:DOWNLOADER_MIDDLEWARES使刚才写的middlewares中间件中的类,ITEM_PIPELINES是pipelines中的类
1 2 3 4 5 6 7 8 9 10 11 12 13 | BOT_NAME = 'air_history' SPIDER_MODULES = ['air_history.spiders'] NEWSPIDER_MODULE = 'air_history.spiders' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' DOWNLOADER_MIDDLEWARES = { 'air_history.middlewares.AreaSpiderMiddleware': 543, } ITEM_PIPELINES = { 'air_history.pipelines.AirHistoryPipeline': 300, } |
运行¶
1 | 使用scrapy crawl area_spider就可以运行爬虫 |

结果.png
spider全部代码¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | # -*- coding: utf-8 -*- import scrapy from air_history.items import AirHistoryItem class AreaSpiderSpider(scrapy.Spider): name = 'area_spider' allowed_domains = ['aqistudy.cn'] # 爬取的域名,不会超出这个顶级域名 base_url = "https://www.aqistudy.cn/historydata/" start_urls = [base_url] def parse(self, response): print('爬取城市信息....') url_list = response.xpath("//div[@class='all']/div[@class='bottom']/ul/div[2]/li/a/@href").extract() # 全部链接 city_list = response.xpath("//div[@class='all']/div[@class='bottom']/ul/div[2]/li/a/text()").extract() # 城市名称 for url, city in zip(url_list, city_list): url = self.base_url + url yield scrapy.Request(url=url, callback=self.parse_month, meta={'city': city}) def parse_month(self, response): print('爬取{}月份...'.format(response.meta['city'])) url_list = response.xpath('//tbody/tr/td/a/@href').extract() for url in url_list: url = self.base_url + url yield scrapy.Request(url=url, callback=self.parse_day, meta={'city': response.meta['city']}) def parse_day(self, response): print('爬取最终数据...') item = AirHistoryItem() node_list = response.xpath('//tr') node_list.pop(0) # 去除第一行标题栏 for node in node_list: item['data'] = node.xpath('./td[1]/text()').extract_first() item['city'] = response.meta['city'] item['aqi'] = node.xpath('./td[2]/text()').extract_first() item['level'] = node.xpath('./td[3]/text()').extract_first() item['pm2_5'] = node.xpath('./td[4]/text()').extract_first() item['pm10'] = node.xpath('./td[5]/text()').extract_first() item['so2'] = node.xpath('./td[6]/text()').extract_first() item['co'] = node.xpath('./td[7]/text()').extract_first() item['no2'] = node.xpath('./td[8]/text()').extract_first() item['o3'] = node.xpath('./td[9]/text()').extract_first() yield item |
