Scrapy是Python开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。
url:https://www.lfd.uci.edu/~gohlke/pythonlibs/
pip install scrapy
爬取天气网城市的信息
url : https://www.aqistudy.cn/historydata/
爬取主要的信息: 热门城市每一天的空气质量信息
点击月份还有爬取每天的空气质量信息
scrapy startproject weather_spider
cd到根目录,运行scrapy genspider weather www.aqistudy.cn/historydata
这里的weather是spider的名字
对于scrapy,第一步,必须编写item.py,明确爬取的对象
import scrapy
class WeatherSpiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
"""日期 AQI 质量等级 PM2.5 PM10 SO2 CO NO2 O3_8h"""
city = scrapy.Field()
date = scrapy.Field()
aqi = scrapy.Field()
level = scrapy.Field()
pm25 = scrapy.Field()
pm10 = scrapy.Field()
so2 = scrapy.Field()
co = scrapy.Field()
no2 = scrapy.Field()
o3_8h = scrapy.Field()
对于爬取必须伪装好UA,在setting.py中定义MY_USER_AGENT
来存放UA,注意在settings中命名必须大写
MY_USER_AGENT = [
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
]
在定义好UA后,在middlewares.py中创建RandomUserAgentMiddleware
类
import random
class RandomUserAgentMiddleware(object):
def __init__(self, user_agents):
self.user_agents = user_agents
@classmethod
def from_crawler(cls, crawler):
# 从settings.py中导入MY_USER_AGENT
s = cls(user_agents=crawler.settings.get('MY_USER_AGENT'))
return s
def process_request(self, request, spider):
agent = random.choice(self.user_agents)
request.headers['User-Agent'] = agent
return None
注意要在settings.py中激活,必须是900,来去掉scrapy本身的UA
DOWNLOADER_MIDDLEWARES = {
'weather_spider.middlewares.RandomUserAgentMiddleware':900,
}
开始编写最重要的spider.py,推荐使用scrapy.shell来一步一步调试
在scrapy中xpath方法和lxml中的xpath语法一样
我们可以看出url中缺少前面的部分,follow方法可以自动拼接url,通过meta方法来传递需要保存的city名字,通过callback方法来调度将下一个爬取的URL
def parse(self, response):
city_urls = response.xpath('//div[@class="all"]/div[@class="bottom"]//li/a/@href').extract()[16:17]
city_names = response.xpath('//div[@class="all"]/div[@class="bottom"]//li/a/text()').extract()[16:17]
self.logger.info('正在爬去{}城市url'.format(city_names[0]))
for city_url, city_name in zip(city_urls, city_names):
# 用的follow快捷方式,可以自动拼接url
yield response.follow(url=city_url, meta={'city': city_name}, callback=self.parse_month)
这时就是定义parse_month函数,首先分析月份的详情页,拿到月份的url
还是在scrapy.shell 中一步一步调试
通过follow方法拼接url,meta来传递city_name要保存的城市名字,selenium:True先不管
然后通过callback方法来调度将下一个爬取的URL,即就是天的爬取详细页
def parse_month(self, response):
"""
解析月份的url
:param response:
:return:
"""
city_name = response.meta['city']
self.logger.info('正在爬取{}城市的月份url'.format(city_name[0]))
# 由于爬取的信息太大了,所有先爬取前5个
month_urls = response.xpath('//ul[@class="unstyled1"]/li/a/@href').extract()[0:5]
for month_url in month_urls:
yield response.follow(url=month_url, meta={'city': city_name, 'selenium': True}, callback=self.parse_day_data)
现在将日的详细页的信息通过xpah来取出
发现竟然为空
同时发现了源代码没有该信息
说明了是通过js生成的数据,scrapy只能爬静态的信息,所以引出的scrapy对接selenium的知识点,所以上面meta传递的参数就是告诉scrapy使用selenium来爬取。
复写WeatherSpiderDownloaderMiddleware
下载中间件中的process_request函数方法
middlewares.py
import time
import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class WeatherSpiderDownloaderMiddleware(object):
def process_request(self, request, spider):
if request.meta.get('selenium'):
# 为了让浏览器能够无界面的工作
chrome_options = Options()
# 设置chrome浏览器无界面模式
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options)
# 用浏览器去访问这个地址
driver.get(request.url)
time.sleep(1.5) # 因为浏览器需要加载渲染
html = driver.page_source
driver.quit()
return scrapy.http.HtmlResponse(url=request.url, body=html, encoding='utf-8', request=request)
return None
激活WeatherSpiderDownloaderMiddleware
DOWNLOADER_MIDDLEWARES = {
'weather_spider.middlewares.WeatherSpiderDownloaderMiddleware': 543,
'weather_spider.middlewares.RandomUserAgentMiddleware':900,
}
最后编写weather.py中的剩下代码
from ..items import WeatherSpiderItem
def parse_day_data(self, response):
"""
解析每天的数据
:param response:
:return:
"""
node_list = response.xpath('//tr')
# 去掉表头
node_list.pop(0)
print(response.body)
print('开始爬取……')
print(node_list)
for node in node_list:
item = WeatherSpiderItem
item['city'] = response.meta['city']
item['date'] = node.xpath('./td[1]/text()').extract_first()
item['aqi'] = node.xpath('./td[2]/text()').extract_first()
item['level'] = node.xpath('./td[3]//text()').extract_first()
item['pm25'] = 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_8h'] = node.xpath('./td[9]/text()').extract_first()
yield item
一定要注意项目的根目录执行命令,可以通过scrapy list
查看是否存在项目
scrapy保存信息的最简单的方法主要有四种,-o 输出指定格式的文件,命令如下:
默认json
json lines格式,默认为Unicode编码
csv 逗号表达式,可用Excel打开
xml格式
但是保存的编码不对,必须在settings中加入FEED_EXPORT_ENCODING = 'utf-8'
这里入的库是Mongodb,在settings.py中配置
MONGO_URI='192.168.96.128' #虚拟机ip
MONGO_DB='weather' #表名
对于入门主要处理的是pipelines中
import pymongo
class MongoPipeline(object):
def __init__(self,mongo_uri,mongo_db):
self.mongo_uri=mongo_uri
self.mongo_db=mongo_db
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DB')
)
def open_spider(self, spider): # 当爬虫开启时连接MongoDB数据库
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]
def process_item(self, item, spider):
name = item.__class__.__name__
self.db[name].insert(dict(item)) # 保存数据
return item
def close_spider(self, spider): # 当爬虫关闭时关闭数据库连接
self.client.close()
ITEM_PIPELINES = {
'weather_spider.pipelines.MongoPipeline': 300,
}
效果如下
我们本次通过爬取天气网站的来作为学习 Scrapy 的,这里展示的关于 Scrapy 大部分的知识点。如果改写列表,就可以爬取北京所有的天气信息,当然还可以爬取全部城市的天气信息,即这个天气网的全部内容基本都爬取。