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中命名必须大写
- settings.py
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类
- middlewares.py
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
开始编写最重要的spider.py,推荐使用scrapy.shell来一步一步调试
- 先拿到所有的城市
在scrapy中xpath方法和lxml中的xpath语法一样
我们可以看出url中缺少前面的部分,follow方法可以自动拼接url,通过meta方法来传递需要保存的city名字,通过callback方法来调度将下一个爬取的URL
- weather.py
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,即就是天的爬取详细页
- weather.py
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:
“”"
文末有福利领取哦~
👉一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
👉二、Python必备开发工具
👉三、Python视频合集
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
👉 四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。(文末领读者福利)
👉五、Python练习题
检查学习结果。
👉六、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!