“清明时节雨纷纷,路上行人欲断魂”
这句话传唱了千百年,大多数人也习惯了每年清明的时候会下雨,我就一直很好奇,难道清明节全中国都会下雨吗?于是今天准备获取一下清明节当天全国的天气数据来,然后通过数据可视化来看一下,到底哪些地方没有下雨!
一开始准备直接从中国天气网(https://www.weather.com.cn/)拿取天气数据,找到了一个获取城市天气数据的通用地址:
http://www.weather.com.cn/weathern/{城市代码}.shtml
经过一顿操作之后发现短时间内没搞清楚怎么去获取他的城市代码,于是换了一个思路,找到了另外一个方法。
使用一个免费的api提供网站,每个账号每天可以调用接口1w次(良心好评
),使用需要账号创建的key,具体可以看下面的文档:
https://dev.qweather.com/docs/api/weather/weather-now/
然后主要使用两个接口:
获取从当前开始3天内的天气(另有其他时间段,as you wish)
https://devapi.qweather.com/v7/weather/3d?location={城市id}&key=YOUR_KEY
获取每个城市的id(通过省份会返回下面的市/县数据,但是会有一些其他数据。比如:河北省会返回日本河北市,后面会过滤掉)
https://geoapi.qweather.com/v2/city/lookup?location={省份}&key=YOUR_KEY
问题来了,这么多城市手动去统计感觉好麻烦,还要区分是哪个。看到中国天气网上面好像可以直接取数据,于是......
正式开始
1.通过解析html数据获取网页上面的省份数据
import requests
from parsel import Selector
import json
#获取省份信息
def getProvinces():
province = []
url_province = 'http://www.weather.com.cn/weathern/101070201.shtml'
re = requests.get(url=url_province)
select = Selector(re.content.decode('utf-8'))#构建selector
result_province = select.xpath("/html/body/div[4]/div[1]/div/div/a")#使用上图中复制的xpath获取所有的a标签数据
for url_privince in result_province:
url = url_privince.xpath('@href').extract_first()#获取每个a标签的网址,省气象网站
text = url_privince.xpath('text()').extract_first()#获取每个a标签的文本内容,省
province.append(text)
return province
2.通过接口获取天气数据存放到本地文件
def getWeather(provinces,key):
for province in provinces:
url_citys = f'https://geoapi.qweather.com/v2/city/lookup?location={province}&key={key}'
res_city = requests.get(url_citys)
data_city = json.loads(res_city.text)#城市id数据
for city in data_city['location']:
if city['country'] == '中国' and province in city['adm1'] :#过滤其他国家的数据
url_weather = f"https://devapi.qweather.com/v7/weather/3d?location={city['id']}&key={key}"
res_weather = requests.get(url_weather)
data_city = json.loads(res_weather.text)#城市天气数据
try:
for day in data_city['daily']:
if day['fxDate'] == '2023-04-05':#只获取清明节当天的数据
textDay = day['textDay'] # 白天天气情况
tempMax = day['tempMax'] # 最高温
tempMin = day['tempMin'] # 最低温
precip = day['precip'] # 总降水量
path = r'C:\Users\edz\Desktop\excel\weather.csv'#存放地址
with open(path, 'a+') as f:
line = province + ',' + city[
'name'] + ',' + textDay + ',' + tempMin + ',' + tempMax + ',' + precip + '\n'
f.write(line)
except Exception as e:
print('error: %s' % e)
3.执行
if __name__ == '__main__':
key = '73d20be1a74a43fea3894f72d8fbc845'
provinces = getProvinces()
getWeather(provinces,key)
执行之后会在存放路径生成一个名叫weather.csv的文件,样式如下:
接下来我们可以使用永洪desktop数据可视化工具(免费且炒鸡好用的数据可视化工具,门槛极低)
下载链接:https://www.yonghongtech.com/cp/desktop/
4.打开永洪可视化工具,然后选择数据集-Excel数据集-上传csv文件保存
5.使用制作报告-新建报告制作地图可视化,最后上结果
全国各地降雨分布情况清清楚楚,有木有很简单!
如果有其他问题可以通过公众号联系作者
FunTester原创专题推荐~~
-- By FunTester