爬取某地全年天气信息
所用代码是根据一位博主的代码修改的,想看具体的原理可以通过下面地址。
原博主参考代码地址
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 13:36:42 2020
@author: ZAN
"""
import requests
import json
import pandas as pd
import re
# from bs4 import BeautifulSoup
headers = {}
headers['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36' #http头大小写不敏感
headers['accept'] = '*/*'
headers['Connection'] = 'keep-alive'
headers['Pragma'] = 'no-cache'
result = []
for date in range (0,12):
url = "http://tianqi.2345.com/t/wea_history/js/"+str(date+201601)+"/57447_"+str(date+201601)+".js" # 57447 ,代表恩施
res = requests.get(url)
a=res.text
data=json.dumps(a, indent=2,ensure_ascii=False)
#print(data[17:])
b=a.split('[')
#print(a)
#print(b[1])
c=b[1].replace('"','')
#d=c.split(',')
#e=str(d).split("{")
#print(e)
f=re.findall(r'\{(.*?)\}', str(c))
#g=re.findall(r'\{(.*?)\}', str(f))
#print(f[:])
tianqi=[]
for i in f[:-1]:
i={i.replace("'",'')}
xx= re.sub("[A-Za-z\!\%\[\]\,\。]", " ", str(i))
yy=xx.split(' ')
#print(yy)
tianqi.append([data[24:26], yy[3][1:], yy[10][1:-1], yy[17][1:-1], yy[24][1:], yy[34][1:],yy[41][1:], yy[45][1:],yy[53][1:]])
#print(tianqi)
result = result + tianqi
#print('日期 最高气温 最低气温 天气 风向风力 空气质量指数')
# print(tianqi)
weather=pd.DataFrame(result)
weather.to_csv(str(data[24:26])+'.csv',encoding="utf_8_sig")
主要就是把原代码中url中的日期参数改用变量替代了,用for循环抓取12个月的数据,通过list合并后再转成dateframe格式。有需要的小伙伴可以直接拿去用,只用把代表地点的参数和日期参数改下就可以用了。想知道轮子咋造的可以看原博主的文章,链接在文首。

浙公网安备 33010602011771号