设为首页收藏本站

安徽论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 10325|回复: 0

python将天气预报可视化

[复制链接]

110

主题

0

回帖

342

积分

中级会员

Rank: 3Rank: 3

积分
342
发表于 2022-3-26 11:01:28 | 显示全部楼层 |阅读模式
网站内容均来自网络,本站只提供信息平台,如有侵权请联系删除,谢谢!
目录


前言

在想题材之际,打开私信,有许多萌新&小伙伴询问我之前写的一篇《python爬取天气预报数据,并实现数据可视化》中的bug怎么解决,虽然我在之前,就在评论区提供了自己的解决思路,但可能不够清楚,于是写这篇文章,来解决bug,并对程序进行优化。

结果展示

其中:
红线代表当天最高气温,蓝线代表最低气温,最高气温点上的标注为当天的天气情况。
如果使夜晚运行程序,则最高气温和最低气温的点会重合,使由爬取数据产生误差导致的。


程序代码

详细请看注释
  1. # -*- coding: UTF-8 -*-
  2. """
  3. # @Time: 2022/1/4 11:02
  4. # @Author: 远方的星
  5. # @CSDN: https://blog.csdn.net/qq_44921056
  6. """
  7. import chardet
  8. import requests
  9. from lxml import etree
  10. from fake_useragent import UserAgent
  11. import pandas as pd
  12. from matplotlib import pyplot as plt


  13. # 随机产生请求头
  14. ua = UserAgent(verify_ssl=False, path='D:/Pycharm/fake_useragent.json')


  15. # 随机切换请求头
  16. def random_ua():
  17.     headers = {
  18.         "user-agent": ua.random
  19.     }
  20.     return headers


  21. # 解析页面
  22. def res_text(url):
  23.     res = requests.get(url=url, headers=random_ua())
  24.     res.encoding = chardet.detect(res.content)['encoding']
  25.     response = res.text
  26.     html = etree.HTML(response)
  27.     return html


  28. # 获得未来七天及八到十五天的页面链接
  29. def get_url(url):
  30.     html = res_text(url)
  31.     url_7 = 'http://www.weather.com.cn/' + html.xpath('//*[@id="someDayNav"]/li[2]/a/@href')[0]
  32.     url_8_15 = 'http://www.weather.com.cn/' + html.xpath('//*[@id="someDayNav"]/li[3]/a/@href')[0]
  33.     # print(url_7)
  34.     # print(url_8_15)
  35.     return url_7, url_8_15


  36. # 获取未来七天的天气情况
  37. def get_data_7(url):
  38.     html = res_text(url)
  39.     list_s = html.xpath('//*[@id="7d"]/ul/li')  # 获取天气数据列表
  40.     Date, Weather, Low, High = [], [], [], []
  41.     for i in range(len(list_s)):
  42.         list_date = list_s[i].xpath('./h1/text()')[0]  # 获取日期,如:4日(明天)
  43.         # print(list_data)
  44.         list_weather = list_s[i].xpath('./p[1]/@title')[0]  # 获取天气情况,如:小雨转雨夹雪
  45.         # print(list_weather)
  46.         tem_low = list_s[i].xpath('./p[2]/i/text()')  # 获取最低气温
  47.         tem_high = list_s[i].xpath('./p[2]/span/text()')  # 获取最高气温
  48.         if tem_high == []:  # 遇到夜晚情况,筛掉当天的最高气温
  49.             tem_high = tem_low  # 无最高气温时,使最高气温等于最低气温
  50.         tem_low = int(tem_low[0].replace('℃', '')) # 将气温数据处理
  51.         tem_high = int(tem_high[0].replace('℃', ''))
  52.         # print(type(tem_high))
  53.         Date.append(list_date), Weather.append(list_weather), Low.append(tem_low), High.append(tem_high)
  54.     excel = pd.DataFrame()  # 定义一个二维列表
  55.     excel['日期'] = Date
  56.     excel['天气'] = Weather
  57.     excel['最低气温'] = Low
  58.     excel['最高气温'] = High
  59.     # print(excel)
  60.     return excel


  61. def get_data_8_15(url):
  62.     html = res_text(url)
  63.     list_s = html.xpath('//*[@id="15d"]/ul/li')
  64.     Date, Weather, Low, High = [], [], [], []
  65.     for i in range(len(list_s)):
  66.         # data_s[0]是日期,如:周二(11日),data_s[1]是天气情况,如:阴转晴,data_s[2]是最低温度,如:/-3℃
  67.         data_s = list_s[i].xpath('./span/text()')
  68.         # print(data_s)
  69.         date = modify_str(data_s[0])  # 获取日期情况
  70.         weather = data_s[1]
  71.         low = int(data_s[2].replace('/', '').replace('℃', ''))
  72.         high = int(list_s[i].xpath('./span/em/text()')[0].replace('℃', ''))
  73.         # print(date, weather, low, high)
  74.         Date.append(date), Weather.append(weather), Low.append(low), High.append(high)
  75.     # print(Date, Weather, Low, High)
  76.     excel = pd.DataFrame()  # 定义一个二维列表
  77.     excel['日期'] = Date
  78.     excel['天气'] = Weather
  79.     excel['最低气温'] = Low
  80.     excel['最高气温'] = High
  81.     # print(excel)
  82.     return excel


  83. # 将8-15天日期格式改成与未来7天一致
  84. def modify_str(date):
  85.     date_1 = date.split('(')
  86.     date_2 = date_1[1].replace(')', '')
  87.     date_result = date_2 + '(' + date_1[0] + ')'
  88.     return date_result


  89. # 实现数据可视化
  90. def get_image(date, weather, high, low):
  91.     # 用来正常显示中文标签
  92.     plt.rcParams['font.sans-serif'] = ['SimHei']
  93.     # 用来正常显示负号
  94.     plt.rcParams['axes.unicode_minus'] = False
  95.     # 根据数据绘制图形
  96.     fig = plt.figure(dpi=128, figsize=(10, 6))
  97.     ax = fig.add_subplot(111)
  98.     plt.plot(date, high, c='red', alpha=0.5, marker='*')
  99.     plt.plot(date, low, c='blue', alpha=0.5, marker='o')
  100.     # 给图表中两条折线中间的部分上色
  101.     plt.fill_between(date, high, low, facecolor='blue', alpha=0.2)
  102.     # 设置图表格式
  103.     plt.title('邳州近15天天气预报', fontsize=24)
  104.     plt.xlabel('日期', fontsize=12)
  105.     # 绘制斜的标签,以免重叠
  106.     fig.autofmt_xdate()
  107.     plt.ylabel('气温', fontsize=12)
  108.     # 参数刻度线设置
  109.     plt.tick_params(axis='both', which='major', labelsize=10)
  110.     # 修改刻度
  111.     plt.xticks(date[::1])
  112.     # 对点进行标注,在最高气温点处标注当天的天气情况
  113.     for i in range(15):
  114.         ax.annotate(weather[i], xy=(date[i], high[i]))
  115.     # 显示图片
  116.     plt.show()


  117. def main():
  118.     base_url = 'http://www.weather.com.cn/weather1d/101190805.shtml'
  119.     url_7, url_8_15 = get_url(base_url)
  120.     data_1 = get_data_7(url_7)
  121.     data_2 = get_data_8_15(url_8_15)
  122.     data = pd.concat([data_1, data_2], axis=0, ignore_index=True)  # ignore_index=True实现两张表拼接,不保留原索引
  123.     get_image(data['日期'], data['天气'], data['最高气温'], data['最低气温'])


  124. if __name__ == '__main__':
  125.     main()
复制代码
期望

这是以一个城市为例的可视化,下次争取做到根据输入的城市进行天气预报可视化
到此这篇关于python将天气预报可视化的文章就介绍到这了,更多相关python天气预报内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
                                                        
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
免责声明
1. 本论坛所提供的信息均来自网络,本网站只提供平台服务,所有账号发表的言论与本网站无关。
2. 其他单位或个人在使用、转载或引用本文时,必须事先获得该帖子作者和本人的同意。
3. 本帖部分内容转载自其他媒体,但并不代表本人赞同其观点和对其真实性负责。
4. 如有侵权,请立即联系,本网站将及时删除相关内容。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表