当前位置 博文首页 > hhladminhhl的博客:不知道天气咋样?一起用Python爬取天气数据
今天我们分享一个小案例,获取天气数据,进行可视化分析,带你直观了解天气情况!
总体来说,我们需要先对中国天气网中的天气数据进行爬取,保存为csv文件,并将这些数据进行可视化分析展示。
拆解需求,大致可以整理出我们需要分为以下几步完成:
首先我们需要获取各个城市的降雨数据,通过对中国天气网网址分析发现,城市的天气网址为:http://www.weather.com.cn/weather/101180101.shtml。
根据对数据分析,返回的json格式数据,不难发现:
网页结构我们上面已经分析好了,那么我们就可以来动手爬取所需要的数据了。获取到所有的数据资源之后,可以把这些数据保存下来。
请求网站:
天气网的网址:http://www.weather.com.cn/weather/101180101.shtml。如果想爬取不同的地区只需修改最后的101180101地区编号,前面的weather代表是7天的网页。
def getHTMLtext(url):
"""请求获得网页内容"""
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
print("Success")
return r.text
except:
print("Fail")
return" "
处理数据:
采用BeautifulSoup库对刚刚获取的字符串进行数据提取。获取我们需要的风力方向,风级,降水量,相对湿度,空气质量等。
def get_content(html,cityname):
"""处理得到有用信息保存数据文件"""
final = [] # 初始化一个列表保存数据
bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象
body = bs.body
data = body.find('div', {'id': '7d'}) # 找到div标签且id = 7d
# 下面爬取当天的数据
data2 = body.find_all('div',{'class':'left-div'})
text = data2[2].find('script').string
text = text[text.index('=')+1 :-2] # 移除改var data=将其变为json数据
jd = json.loads(text)
dayone = jd['od']['od2'] # 找到当天的数据
final_day = [] # 存放当天的数据
count = 0
for i in dayone:
temp = []
if count <=23:
temp.append(i['od21']) # 添加时间
temp.append(cityname+'市') # 添加城市
temp.append(i['od22']) # 添加当前时刻温度
temp.append(i['od24']) # 添加当前时刻风力方向
temp.append(i['od25']) # 添加当前时刻风级
temp.append(i['od26']) # 添加当前时刻降水量
temp.append(i['od27']) # 添加当前时刻相对湿度
temp.append(i['od28']) # 添加当前时刻控制质量
# print(temp)
final_day.append(temp)
data_all.append(temp)
count = count +1
# 下面爬取24h的数据
ul = data.find('ul') # 找到所有的ul标签
li = ul.find_all('li') # 找到左右的li标签
i = 0 # 控制爬取的天数
for day in li: # 遍历找到的每一个li
if i < 7 and i > 0:
temp = [] # 临时存放每天的数据
date = day.find('h1').string # 得到日期
date = date[0:date.index('日')] # 取出日期号
temp.append(date)
inf = day.find_all('p') # 找出li下面的p标签,提取第一个p标签的值,即天气
temp.append(inf[0].string)
tem_low = inf[1].find('i').string # 找到最低气温
if inf[1].find('span') is None: # 天气预报可能没有最高气温
tem_high = None
else:
tem_high = inf[1].find('span').string # 找到最高气温
temp.append(tem_low[:-1])
if tem_high[-1] == '℃':
temp.append(tem_high[:-1])
else:
temp.append(tem_high)
wind = inf[2].find_all('span') # 找到风向
for j in wind:
temp.append(j['title'])
wind_scale = inf[2].find('i').string # 找到风级
index1 = wind_scale.index('级')
temp.append(int(wind_scale[index1-1:index1]))
final.append(temp)
i = i + 1
return final_day,final
城市的天气数据拿到了,同理我们可以根据不同的地区编号获取河南省各个地级市的天气数据。
Citycode = { "郑州": "101180101",
"新乡": "101180301",
"许昌": "101180401",
"平顶山": "101180501",
"信阳": "101180601",
"南阳": "101180701",
"开封": "101180801",
"洛阳": "101180901",
"商丘": "101181001",
"焦作": "101181101",
"鹤壁": "101181201",
"濮阳": "101181301",
"周口": "101181401",
"漯河": "101181501",
"驻马店": "101181601",
"三门峡": "101181701",
"济源": "101181801",
"安阳": "101180201"}
citycode_lists = list(Citycode.items())
for city_code in citycode_lists:
city_code = list(city_code)
print(city_code)
citycode = city_code[1]
cityname = city_code[0]
url1 = 'http://www.weather.com.cn/weather/'+citycode+ '.shtml' # 24h天气中国天气网
html1 = getHTMLtext(url1)
data1, data1_7 = get_content(html1,cityname) # 获得1-7天和当天的数据
存储数据:
def write_to_csv(file_name, data, day=14):
"""保存为csv文件"""
with open(file_name, 'a', errors='ignore', newline='') as f:
if day == 14:
header = ['日期','城市','天气','最低气温','最高气温','风向1','风向2','风级']
else:
header = ['小时','城市','温度','风力方向','风级','降水量','相对湿度','空气质量']
f_csv = csv.writer(f)
f_csv.writerow(header)
f_csv.writerows(data)
write_to_csv('河南天气.csv',data_all,1)
这样我们就可以把全省的各个地级市天气数据保存下来了。
统计全省的风力和风向,因为风力风向使用极坐标的方式展现比较清晰,所以我们采用极坐标的方式展现一天的风力风向图,将圆分为8份,每一份代表一个风向,半径代表平均风力,并且随着风级增高,蓝色加深。
def wind_radar(data):
"""风向雷达图"""
wind = list(data['风力方向'])
wind_speed = list(data['风级'])
for i in range(0,24