为了爬取天气数据,我们通常需要一个支持天气API的服务。免费的天气API如OpenWeatherMap是一个很好的选择。以下,我将提供一个简单的Python示例,使用requests
库来从OpenWeatherMap API获取天气数据,并使用json
库来解析返回的JSON数据。
步骤 1: 注册并获取API密钥
首先,你需要在OpenWeatherMap注册一个账户,并获取一个API密钥(API Key)。这个密钥将被用于你的请求中以验证你的身份。
步骤 2: 安装Python库
你需要安装requests
库,如果还未安装,可以通过pip安装:
pip install requests
步骤 3: 编写Python脚本来获取天气数据
1、数据获取
请求网站链接
首先查看中国天气网的网址:http://www.weather.com.cn/weather/101280701.shtml这里就访问本地的天气网址,如果想爬取不同的地区只需修改最后的101280701地区编号即可,前面的weather代表是7天的网页,weather1d代表当天,weather15d代表未来14天。这里就主要访问7天和14天的中国天气网。采用requests.get()
方法,请求网页,如果成功访问,则得到的是网页的所有字符串文本。这就是请求过程。
def getHTMLtext(url):
"""请求获得网页内容"""
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
print("成功访问")
return r.text
except:
print("访问错误")
return" "
提取有用信息
这里采用BeautifulSoup库对刚刚获取的字符串进行数据提取,首先对网页进行检查,找到需要获取数据的标签:
可以发现7天的数据信息在div标签中并且id=“7d”,并且日期、天气、温度、风级等信息都在ul和li标签中,所以我们可以使用BeautifulSoup对获取的网页文本进行查找div标签id=“7d”,找出他包含的所有的ul和li标签,之后提取标签中相应的数据值,保存到对应列表中。
这里要注意一个细节就是有时日期没有最高气温,对于没有数据的情况要进行判断和处理。另外对于一些数据保存的格式也要提前进行处理,比如温度后面的摄氏度符号,日期数字的提取,和风级文字的提取,这需要用到字符查找及字符串切片处理。
def get_content(html):
"""处理得到有用信息保存数据文件"""
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(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)
count = count +1
下面爬取7天的数据
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
同样对于/weather15d:15天的信息,也做同样的处理,这里经过查看后发现他的15天网页中只有8-14天,前面的1-7天在/weather中,这里就分别访问两个网页将爬取得到的数据进行合并得到最终14天的数据。- 前面是未来14天的数据爬取过程,对于当天24小时的天气信息数据,经过查找发现他是一个json数据,可以通过json.loads()
方法获取当天的数据,进而对当天的天气信息进行提取。
保存csv文件
前面将爬取的数据添加到列表中,这里引入csv库,利用f_csv.writerow(header)和f_csv.writerows(data)方法,分别写入表头和每一行的数据,这里将1天和未来14天的数据分开存储,分别保存为weather1.csv和weather14.csv,下面是他们保存的表格图:
2.可视化分析
当天温度变化曲线图
采用matplotlib中plt.plot()方法绘制出一天24小时的温度变化曲线,并用plt.text()方法点出最高温和最低温,并画出平均温度线,下图为温度变化曲线图:(代码见附录)
分析可以发现这一天最高温度为33℃,最低温度为28℃,并且平均温度在20.4℃左右,通过对时间分析,发现昼夜温差5℃,低温分布在凌晨,高温分布在中午到下午的时间段。
当天相对湿度变化曲线图
采用matplotlib中plt.plot()方法绘制出一天24小时的湿度变化曲线,并画出平均相对湿度线,下图为湿度变化曲线图:(代码见附录)
分析可以发现这一天最高相对湿度为86%,最低相对湿度为58℃,并且平均相对湿度在75%左右,通过对时间分析,清晨的湿度比较大,而下午至黄昏湿度较小。
风向风级雷达图
统计一天的风力和风向,由于风力风向使用极坐标的方式展现较好,所以这里采用的是极坐标的方式展现一天的风力风向图,将圆分为8份,每一份代表一个风向,半径代表平均风力,并且随着风级增高,蓝色加深,最后结果如下所示:
分析可以发现这一天西南风最多,平均风级达到了1.75级,东北风也有小部分1.0级,其余空白方向无来风。
未来14天高低温变化曲线图
统计未来14天的高低温度变化,并绘制出他们的变化曲线图,分别用虚线将他们的平均气温线绘制出来,最后结果如下所示:
分析可以发现未来14天高温平均气温为30.5℃,温度还是比较高,但是未来的第8天有降温,需要做好降温准备,低温前面处于平稳趋势,等到第8天开始下降,伴随着高温也下降,整体温度下降,低温平均在27℃左右。
未来14天风向风级雷达图
统计未来14天的风向和平均风力,并和前面一样采用极坐标形式,将圆周分为8个部分,代表8个方向,颜色越深代表风级越高,最后结果如下所示:
分析可以发现未来14天东南风、西南风所占主要风向,风级最高达到了5级,最低的西风平均风级也有3级。
未来14天气候分布饼图
统计未来14天的气候,并求每个气候的总天数,最后将各个气候的饼图绘制出来,结果如下所示:
分析可以发现未来14天气候基本是“雨”、“阴转雨”和“阵雨”,下雨的天数较多,结合前面的气温分布图可以看出在第8-9天气温高温下降,可以推测当天下雨,导致气温下降。
4、代码框架
代码主要分为weather.py:对中国天气网进行爬取天气数据并保存csv文件;data1_analysis.py:对当天的天气信息进行可视化处理;data14_analysis.py:对未来14天的天气信息进行可视化处理。下面是代码的结构图:
附源代码
weather.py
# weather.py
import requests
from bs4 import BeautifulSoup
import csv
import json
def getHTMLtext(url):
"""请求获得网页内容"""
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
print("成功访问")
return r.text
except:
print("访问错误")
return" "
def get_content(html):
"""处理得到有用信息保存数据文件"""
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(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)
count = count +1
# 下面爬取7天的数据
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
#print(final)
def get_content2(html):
"""处理得到有用信息保存数据文件"""
final = [] # 初始化一个列表保存数据
bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象
body = bs.body
data = body.find('div', {<!-- -->'id': '15d'}) # 找到div标签且id = 15d
ul = data.find('ul') # 找到所有的ul标签
li = ul.find_all('li') # 找到左右的li标签
final = []
i = 0 # 控制爬取的天数
for day in li: # 遍历找到的每一个li
if i < 8:
temp = [] # 临时存放每天的数据
date = day.find('span',{<!-- -->'class':'time'}).string # 得到日期
date = date[date.index('(')+1:-2] # 取出日期号
temp.append(date)
weather = day.find('span',{<!-- -->'class':'wea'}).string # 找到天气
temp.append(weather)
tem = day.find('span',{<!-- -->'class':'tem'}).text # 找到温度
temp.append(tem[tem.index('/')+1:-1]) # 找到最低气温
temp.append(tem[:tem.index('/')-1]) # 找到最高气温
wind = day.find('span',{<!-- -->'class':'wind'}).string # 找到风向
if '转' in wind: # 如果有风向变化
temp.append(wind[:wind.index('转')])
temp.append(wind[wind.index('转')+1:])
else: # 如果没有风向变化,前后风向一致
temp.append(wind)
temp.append(wind)
wind_scale = day.find('span',{<!-- -->'class':'wind1'}).string # 找到风级
index1 = wind_scale.index('级')
temp.append(int(wind_scale[index1-1:index1]))
final.append(temp)
return final
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)
def main():
"""主函数"""
print("Weather test")
# 珠海
url1 = 'http://www.weather.com.cn/weather/101280701.shtml' # 7天天气中国天气网
url2 = 'http://www.weather.com.cn/weather15d/101280701.shtml' # 8-15天天气中国天气网
html1 = getHTMLtext(url1)
data1, data1_7 = get_content(html1) # 获得1-7天和当天的数据
html2 = getHTMLtext(url2)
data8_14 = get_content2(html2) # 获得8-14天数据
data14 = data1_7 + data8_14
#print(data)
write_to_csv('weather14.csv',data14,14) # 保存为csv文件
write_to_csv('weather1.csv',data1,1)
if __name__ == '__main__':
main()
关于Python学习指南
学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!
包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!
————————————————
**全套Python学习资料分享:
👉Python所有方向的学习路线👈
Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取)
👉学习软件
👉全套PDF电子书
👉实战案例
👉Python副业兼职路线&方法👈
学好 Python 不论是就业还是做副业赚钱都不错,但要学会兼职接单还是要有一个学习规划。
👉 这份完整版的Python全套学习资料已经上传,朋友们如果需要可以扫描下方CSDN官方认证二维码或者点击链接免费领取【保证100%免费
】