由于学业需要,本文利用python爬取2345历史天气,爬取年份为2011年到2018年,由于网页格式以及自身编程水平有限,本文分成四个部分爬取2011~2018的历史天气,分别为:2011-2015年,201年1-2月,2016年3-12月,2017年以后。本文爬取的地区是江浙沪皖地区的历史天气。
首先为2011年-2015年的天气代码如下:
#####多个城市循环爬取
###输入待查城市代号
city0=[58362,58343,58141,58044,58238,58259,58357,58246,58354,58131,58027,58151,58245,58248,58457,58465,58659,58452,58450,58453,58549,
58633,58477,58651,58646,58321,58116,58102,58122,58221,58203,58224,58236,58311,58336,58334,58433,58429,58427,58424,70931]
for i in city0:
year=2015
months=["%d%01d"%(year,month+1) for month in range(12)]
todo_urls=[
f"http://tianqi.2345.cn/com/wea_history/js/{i}_{month}.js"
for month in months
]
import requests
datas=[]
for url in todo_urls:
r=requests.get(url)
if r.status_code!=200:
raise Exception()
data=r.text.lstrip("var weather_str=").rstrip(";")
datas.append(data)
import demjson
#解析素有月份数据
all_datas=[]
for data in datas:
tqInfo=demjson.decode(data)["tqInfo"]
city=demjson.decode(data)["city"]
all_datas.extend([x for x in tqInfo if len(x)>0])
len(all_datas)
all_datas[0].keys()
import csv
with open('./'+str(city)+str(year)+'.csv','w',newline='',encoding='utf-8') as csv_file:
writer=csv.writer(csv_file)
columns=['ymd', 'bWendu', 'yWendu', 'tianqi', 'fengxiang'