python爬虫之天气数据分析的示例
创始人
2024-11-20 03:22:38
0次

使用pygal绘图,使用该模块前需先安装pip install pygal,然后导入import pygal

bar = pygal.Line()  # 创建折线图
bar.add('最低气温', lows)   #添加两线的数据序列
bar.add('最高气温', highs)  #注意lows和highs是int型的列表
 
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
bar.x_label_rotation = 45
 
bar.title = cityname+'未来七天气温走向图'   #设置图形标题
bar.x_title = '日期'   #x轴标题
bar.y_title = '气温(摄氏度)'  #  y轴标题
 
bar.legend_at_bottom = True
 
bar.show_x_guides = False
bar.show_y_guides = True
 
bar.render_to_file('temperate1.svg')  # 将图像保存为SVG文件,可通过浏览器查看

最终生成的图形如下图所示,直观的显示了天气情况:

 

python爬虫之天气数据分析的示例

 

完整代码

import csv
import sys
import urllib.request
from bs4 import BeautifulSoup  # 解析页面模块
import pygal
import cityinfo
 
 
cityname = input("请输入你想要查询天气的城市:")
if cityname in cityinfo.city:
    citycode = cityinfo.city[cityname]
else:
    sys.exit()
 
url = '非常抱歉,网页无法访问' + citycode + '.shtml'
header = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36")  # 设置头部信息
http_handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(http_handler)  # 修改头部信息
opener.addheaders = [header]
request = urllib.request.Request(url)  # 制作请求
response = opener.open(request)  # 得到应答包
html = response.read()  # 读取应答包
html = html.decode('utf-8')  # 设置编码,否则会乱码
 
# 根据得到的页面信息进行初步筛选过滤
final = []  # 初始化一个列表保存数据
bs = BeautifulSoup(html, "html.parser")  # 创建BeautifulSoup对象
body = bs.body
data = body.find('div', {'id': '7d'})
print(type(data))
ul = data.find('ul')
li = ul.find_all('li')
 
# 爬取自己需要的数据
i = 0  # 控制爬取的天数
lows = []  # 保存低温
highs = []  # 保存高温
daytimes = []  # 保存日期
weathers = []  # 保存天气
for day in li:  # 便利找到的每一个li
    if i < 7:
        temp = []  # 临时存放每天的数据
        date = day.find('h2').string  # 得到日期
        #print(date)
        temp.append(date)
        daytimes.append(date)
        inf = day.find_all('p')  # 遍历li下面的p标签 有多个p需要使用find_all 而不是find
 
        #print(inf[0].string)  # 提取第一个p标签的值,即天气
        temp.append(inf[0].string)
        weathers.append(inf[0].string)
        temlow = inf[1].find('i').string  # 最低气温
        if inf[1].find('span') is None:  # 天气预报可能没有最高气温
            temhigh = None
            temperate = temlow
        else:
            temhigh = inf[1].find('span').string  # 最高气温
            temhigh = temhigh.replace('℃', '')
            temperate = temhigh + '/' + temlow
        # temp.append(temhigh)
        # temp.append(temlow)
        lowStr = ""
        lowStr = lowStr.join(temlow.string)
        lows.append(int(lowStr[:-1]))  # 以上三行将低温NavigableString转成int类型并存入低温列表
        if temhigh is None:
            highs.append(int(lowStr[:-1]))
        else:
            highStr = ""
            highStr = highStr.join(temhigh)
            highs.append(int(highStr))  # 以上三行将高温NavigableString转成int类型并存入高温列表
        temp.append(temperate)
        final.append(temp)
        i = i + 1
 
# 将最终的获取的天气写入csv文件
with open('weather.csv', 'a', errors='ignore', newline='') as f:
    f_csv = csv.writer(f)
    f_csv.writerows([cityname])
    f_csv.writerows(final)
 
# 绘图
bar = pygal.Line()  # 创建折线图
bar.add('最低气温', lows)
bar.add('最高气温', highs)
 
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
# bar.show_minor_x_labels = False  # 不显示X轴最小刻度
bar.x_label_rotation = 45
 
bar.title = cityname+'未来七天气温走向图'
bar.x_title = '日期'
bar.y_title = '气温(摄氏度)'
 
bar.legend_at_bottom = True
 
bar.show_x_guides = False
bar.show_y_guides = True
 
bar.render_to_file('temperate.svg')

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...