通过气象局网站爬取地方气象信息,并解析字段进行显示。
详细代码如下:
import requests
import json
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
, 'Referer': 'http://www.weather.com.cn/weather1d/101010100.shtml'
}
url = 'http://d1.weather.com.cn/sk_2d/101010100.html?_=1555986533582' # 网络请求地址
response = requests.get(url, headers=headers)
if response.status_code == 200:
response.encoding = 'utf-8'
print(response.text)
json_str = response.text.replace('var dataSK=', '')
json_info = json.loads(json_str)
print('城市:', json_info['cityname'])
print('温度:', json_info['temp'])
print('湿度:', json_info['SD'])
print('风向等级:', json_info['WD'], json_info['WS'])
print('空气PM2.5', json_info['aqi_pm25'])
print()