爬取2345天气数据
学习过一段时间的python,最近自己在独立的爬取数据。有时候遇到问题,在网上搜索出来的结果虽然和你的错误一样,但是就是解决不了自己的问题,我们也不要气馁,要仔细检查你的代码。
在这里我主要爬取2345天气里乌鲁木齐2020年一年的数据,并用Excel保存下来.
我们通过右键查看源代码可以发现,查看不到天气数据,网上说这个网页使用了json格式数据,找到地域ID的JS,但发现根本就没有这个JS,所以我们知道,现在这个网页已经进行了改进。
通过我仔细的查找,发现:右击——检查——Network——点击上一月,出现了一个的GetHistory,找到他的url,即我们要爬取的网页地址。
代码如下:
import requests
import re
import pandas as pd
from bs4 import BeautifulSoup
import json
import numpy as np
#定义空列表,用于保存一年的数据
data = []
wether = []
wind = []
high_tem = []
low_tem = []
quality = []
months = [1,2,3,4,5,6,7,8,9,10,11,12]
for m in months:
url = 'http://tianqi.2345.com/Pc/GetHistory?areaInfo[areaId]=51730&areaInfo[areaType]=2&date[year]=2020&date[month]='+str(m)+''
s = requests.Session()
respone = s.get(url)
if respone.status_code == 200:
html_str = json.loads(respone.text)['data']
resp = re.findall('<td>(.*?)</td>',html_str) #每个月的天气全部数据,返回的是一个列表
new_resp = np.array(resp)
每一天的天气有6个数据,但最高温、最低温和空气质量的数据标签和其余三个不一样,不能一次性全部爬取下来,所以另行爬取。通过findall查找标签可以找到四个数据,我们只取前三个。
n = int(new_resp.shape[0]/4)
c = np.reshape(new_resp,(n,4)) #每四个进行分组,四个为一列表然后通过索引获取
for i in range(0,n,1):
data.append(c[i,0])
wether.append(c[i,1])
wind.append(c[i,2])
result = re.findall('<td style.+?>(.*?)</td>',html_str) #爬取温度数据
new_result = np.array(result)
n = int(new_result.shape[0]/2)
b = np.reshape(new_result,(n,2))
for i in range(0,n,1):
high_tem.append(b[i,0])
low_tem.append(b[i,1])
air = re.findall('<td><span.+?>(.*?)</span></td>',html_str) #爬取空气质量指数数据
for i in air:
quality.append(i)
TQ = pd.DataFrame({'日期':data,'最高温度':high_tem,'最低温度':low_tem,'天气':wether,'风向及风力':wind,'空气质量':quality}) #创建DataFrame表,将数据可视化
最后将数据保存:
TQ.to_excel("weather_data.xlsx",encoding='utf-8')
with open('D:/Learner/天气数据.xls','w',encoding='utf-8') as f:
f.write()