scrapy结合selenium进行动态加载页面内容爬取

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())

百度源代码

但是动态页面使用上述操作后发现,获取到的内容与实际相差很大。

例如我们打开如下页面:

https://www.aqistudy.cn/historydata/monthdata.php?city=北京

右键选择查看网页源代码

查看网页源代码

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

北京空气质量指数

这时打开F12查看Elements 可以看到155在元素中有显示

检查

综上基本可以明白静态页面和动态页面的区别了。

有两种方式可以获取动态页面的内容:

  • 破解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
7
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

随意点击一个地区可以发现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
23
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')
# 指定谷歌浏览器路径
# chrome_options.binary_location = '/root/zx/spider/driver/chromedriver'
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,
}

运行

使用scrapy crawl area_spider就可以运行爬虫

结果

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
 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
您的支持将鼓励我继续创作!