python获取国内城市30天内空气质量指数(AQI)


环保部的网站改了,原来的链接没有了,发送请求的方式也稍微改了一些。

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # 获取国内城市 30天内 每天空气质量指数(AQI)
 4 # 数据来源:中华人民共和国环境保护部
 5 import requests
 6 from bs4 import BeautifulSoup
 7 import datetime
 8 
 9 ref_url = 'http://datacenter.mep.gov.cn:8099/ths-report/report!list.action'
10 req_url = 'http://datacenter.mep.gov.cn:8099/ths-report/report!list.action'
11 
12 
13 def get_html_content(city='西安市', V_DATE='2017-03-01', E_DATE='2017-03-03'):
14     headers = {
15         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
16         'Accept-Encoding': 'gzip, deflate',
17         'Accept-Language': 'zh-CN,zh;q=0.8',
18         'Content-Type': 'application/x-www-form-urlencoded',
19         'Referer': ref_url,
20         'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
21     }
22     data_dict = {
23         'page.pageNo': '1',
24         'xmlname': '1462259560614',
25         'queryflag': 'close',
26         'CITY': city,
27         'isdesignpatterns': 'false',
28         'V_DATE': V_DATE,
29         'E_DATE': E_DATE,
30     }
31     r = requests.post(req_url, data=data_dict, headers=headers, timeout=60)
32     return r.text
33 
34 
35 def date_format():
36     dd = datetime.datetime.now()
37     E_DATE = dd.strftime('%Y-%m-%d')
38     _31DayAgo = (dd - datetime.timedelta(days=31))
39     V_DATE = _31DayAgo.strftime('%Y-%m-%d')
40     return (V_DATE, E_DATE)
41 
42 
43 def get_aqi_info(html_content):
44     soup = BeautifulSoup(html_content, 'html.parser')
45     aqi_table = soup.find(id='GridView1')
46     aqi_trs = aqi_table.find_all('tr')[1:]
47     result = {}
48     for aqi_tr in aqi_trs:
49         aqi_tds = aqi_tr.find_all('td')
50         aqi = aqi_tds[3].string
51         dd = aqi_tds[6].string
52         result[dd] = aqi
53     return result
54 
55 
56 if __name__ == '__main__':
57     city = input('请输入城市名称,如"西安市": ')
58     (V, E) = date_format()
59     content = get_html_content(city, V, E)
60     result = get_aqi_info(content)
61     print(city, '最近30天空气质量指数如下:\n')
62     for key in sorted(result.keys()):
63         print(key, '\t', result[key])

执行的结果类似这样:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM