越来越多的天气开始进行收费了,今天想到用python爬取其他网站上的天气,岂不美哉
import requests as rq
import json
import re
def print_hi(name):
# 城市Id,城市ID对照表放下面了,若是获取可根据IP地址获取地区,然后再对照下面的对照表进行动态获取
cityId = '101110101'
url = 'http://d1.weather.com.cn/weather_index/' + cityId + '.html'
res = rq.get(url)
resText = res.text.encode(res.encoding).decode(res.apparent_encoding)
cityDZ = re.findall(r'var cityDZ =.*?;', resText)[0]
print(cityDZ[12:-1])
dataSK = re.findall(r'var dataSK =.*?;', resText)[0]
print(dataSK[12:-1])
dataZS = re.findall(r'var dataZS =.*?;', resText)[0]
print(dataZS[12:-1])
fc = re.findall(r'var fc =(.*)', resText)[0]
print(fc)
cityDZJson = json.loads(cityDZ[12:-1])
print('城市:' + cityDZJson['weatherinfo']['city'])
print('天气:' + cityDZJson['weatherinfo']['weather'])
print('最高温度:' + cityDZJson['weatherinfo']['temp'])
print('最低温低:' + cityDZJson['weatherinfo']['tempn'])
print('风向:' + cityDZJson['weatherinfo']['wd'])
print('风向强度:' + cityDZJson['weatherinfo']['ws'])
# 其他的字段请自行获取
if __name__ == '__main__':
print_hi('PyCharm')
说我字数太多,不给发布,没办法了,放到git上https://gitee.com/lk666/happy-birthday/blob/master/other/city.js