Python番外篇:selenium+matplotlib 爬取天气预报 制作温度折线图

hello,大家好,我是wangzirui32,今天我们来学习如何使用selenium+matplotlib来爬取天气预报,并制作未来气温折线图。
先来看看成品:
图表
好了,看到了我们的成果,相信你会更有学习的动力的!
开始学习吧!

1. 爬取天气数据并存储到json文件中

1.2 数据来源

这里使用的数据来源为中国天气网(www.weather.com.cn)所提供的天气预报。

1.3 分析天气预报网页

我就以泰州市为例子,未来7天(实际我们要爬取的是未来6天,是不包含今天的天气数据)的天气预报网页为http://www.weather.com.cn/weather/101191201.shtml,可以看出,101191201是城市编号,切换城市编号就可以获取不同城市的天气预报。
开始分析:
ul标签
可以看出,ul中的每一项li标签都是一天的天气数据,继续分析:
li标签好了,分析完毕,开始编写爬取代码。

1.4 编写爬取代码

from selenium.webdriver import Firefox
from datetime import datetime, timedelta
from json import dump

# 城市编号
city_id = 101191201

# url生成
url = "http://www.weather.com.cn/weather/" + str(city_id) + ".shtml"

# executable_path设置为你电脑上浏览器驱动的路径
driver = Firefox(executable_path="geckodriver.exe")

driver.get(url)

# 查找之前分析的ul标签
ul = driver.find_element_by_xpath("//ul[@class='t clearfix']")
# 获取ul里所有的li标签
li_list = ul.find_elements_by_tag_name("li")
# 删除第一项的数据 也就是今天的
del li_list[0]

# 天气数据列表存储我们爬取的所有温度数据
temperature_data_list = []

# 设置当前爬取的日期为1天后
day = 1

for li in li_list:
	# 找到之前分析的p标签
    p = li.find_element_by_css_selector("p.tem")
    
    # 将今天的日期加上day天 然后格式化存储到date中
    date = (datetime.now() + timedelta(days=day)).strftime("%Y-%m-%d")

	# 最高气温和最低气温
	# 说明:[:-1]是为了把内容中末尾的℃符号去掉
    low_temperature = int(p.find_element_by_tag_name("i").text[:-1])
    high_temperature = int(p.find_element_by_tag_name("span").text[:-1])
	
	# 构造数据字典
    dict_temperature = {
    
    "date": date,
                        "low": low_temperature,
                        "high": high_temperature}
	# 存储
    temperature_data_list.append(dict_temperature)

	# 天数+1
    day += 1

with open("temperature.json", "w") as t:
	# 将数据存储至json
    dump(temperature_data_list, t)

运行代码,即可存储天气数据。

2. 读取数据并使用matplotlib制作图表

现在,我们获取加载temperature.json中的数据,用matplotlib制作图表:

import matplotlib.pyplot as plt
from json import load
from datetime import datetime

# 由于matplotlib不支持中文 只好把“泰州”换成“TaiZhou”
city_name = "TaiZhou"

with open("temperature.json") as t:
    data = load(t)
	
	# 准备3个存储数据的列表
    date, high, low = [], [], []

    for d in data:
        date.append(datetime.strptime(d["date"], '%Y-%m-%d'))
        high.append(int(d["high"]))
        low.append(int(d["low"]))

# 开始绘制泰州一周的气温折线图
# 最高气温为红色线 最低为蓝色线
plt.plot(date, high, c='red', linewidth=2)
plt.plot(date, low, c='blue', linewidth=2)
# 在红线和蓝线之前填充一些淡淡的蓝色
plt.fill_between(date, high, low, facecolor='blue', alpha=0.1)
# 给数据设置标签
plt.title("A week's temperature in " + city_name, fontsize=24)
plt.xlabel("Date\nData Source:www.weather.com.cn", fontsize=15)
plt.ylabel("Hightemperature and Lowtemperature", fontsize=15)
# 设置展示格式
plt.tick_params(axis='both', labelsize=10)
# 保存图表
plt.savefig("A week's temperature in " + city_name + ".png", bbox_inches='tight')
# 展示给用户
plt.show()

写在最后

这个程序你还可以有一些“逆天”的操作,比如直接爬取未来40天的温度数据,当然这里作者就不演示了,大家可以自己试一下哦!


好了,这些就是今天的内容,感兴趣的可以点赞收藏,感谢你们!

猜你喜欢

转载自blog.csdn.net/wangzirui32/article/details/113871177