爬虫大法:空气质量数据的爬取
十八大以来,国家开始了一系列治理环境的举措;2015年柴静《穹顶之下》火爆全网,公众开始密切关注PM2.5问题。自此,环境经济学开始了逆袭之旅,从一个冷门学科一跃成为了热门学科。
空气质量数据学者们经常使用的数据之一,但是统计年鉴中很难找到地级市层面的空气质量数据。哪里会提供呢?其实,大家只要百度“PM2.5数据”就会发现中国空气质量在线监测分析平台( https://www.aqistudy.cn/historydata/)提供了全国384个城市和地区详细的空气质量数据。
今天给大家分享的就是爬取中国空气质量在线监测分析平台数据的爬虫程序。这个爬虫程序的思路就是先爬取城市名,然后再爬取各个城市的空气质量数据。因为这个网站网址命名规则是这样的:
https://www.aqistudy.cn/historydata/monthdata.php?city=上海
https://www.aqistudy.cn/historydata/monthdata.php?city=北京
…….
根据上面的思路,经过反复测试,使用下面的代码爬取了384个城市和地区2013年12月至2020年4月的空气质量数据(部分城市是2014年或更晚才有数据):
import requests
from lxml import etree
import urllib.parse
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.204 Safari/537.36'
}
url = "https://www.aqistudy.cn/historydata/"
response = requests.get(url, headers=headers)
text = response.content.decode('utf-8')
html = etree.HTML(text)
city_set = list()
citys = html.xpath("//div[@class='all']/div/ul")
for city in citys:
messages = city.xpath(".//li")
for message in messages:
city_name = message.xpath(".//a/text()")
city_name = "".join(city_name)
# print(city_name)
city_set.append(city_name)
print(city_set)
import time
from urllib import parse
import pandas as pd
from selenium import webdriver
driver = webdriver.PhantomJS(r'D:/爬虫下载/phantomjs-2.1.1-windows\bin\phantomjs.exe')
base_url = 'https://www.aqistudy.cn/historydata/monthdata.php?city='
for k in range(0,len(city_set)):
city = city_set[k]
print(city)
weburl = ('%s%s' % (base_url, parse.quote(city)))
print(weburl)
driver.get(weburl)
time.sleep(1)
dfs = pd.read_html(driver.page_source,header=0)[0]
time.sleep(0.5)
dfs.to_csv(r'D:\爬虫下载\空气质量\%s.csv'% (str(city)),mode='a+',encoding='utf_8_sig')
# dfs.to_csv(r'D:\爬虫下载\空气质量\pm25.csv', mode='a+', encoding='utf_8_sig', index=0)
driver.quit()
print ('爬虫已经爬完!请检测!')
今天给大家分享的是月度空气质量数据,昨天尝试了一下爬取精确到天的数据,由于数据量太大,足足爬了将近七八个小时,我可能后面要优化一下程序再分享给大家。需要本期爬虫代码和爬取下来的月度空气质量数据的朋友,可以在后台私戳我。
说明:因为网站上实际上没有部分城市和地区的空气质量数据(具体是保亭、白沙、昌江、澄迈、儋州、定安、东方、乐东、临高、陵水、琼海、琼中、屯昌、万宁、文昌和五指山这16个城市和地区),所以这些城市和地区爬取下来的会是空白。