python爬取2345天气网上2011年-2018年历史天气

由于学业需要,本文利用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'
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值