python爬取天气数据的实例详解


在本篇文章里小编给大家整理的是一篇关于python爬取天气数据的实例详解内容,有兴趣的朋友们学习下。

就在前几天还是二十多度的舒适温度,今天一下子就变成了个位数,小编已经感受到冬天寒风的无情了。之前对获取天气都是数据上的搜集,做成了一个数据表后,对温度变化的感知并不直观。那么,我们能不能用python中的方法做一个天气数据分析的图形,帮助我们更直接的看出天气变化呢?

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

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

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

 

 完整代码

 1 import csv
 2 import sys
 3 import urllib.request
 4 from bs4 import BeautifulSoup # 解析页面模块
 5 import pygal
 6 import cityinfo
 7  
 8 cityname = input("请输入你想要查询天气的城市:")
 9 if cityname in cityinfo.city:
10   citycode = cityinfo.city[cityname]
11 else:
12   sys.exit()
13 url = '非常抱歉,网页无法访问' + citycode + '.shtml'
14 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") # 设置头部信息
15 http_handler = urllib.request.HTTPHandler()
16 opener = urllib.request.build_opener(http_handler) # 修改头部信息
17 opener.addheaders = [header]
18 request = urllib.request.Request(url) # 制作请求
19 response = opener.open(request) # 得到应答包
20 html = response.read() # 读取应答包
21 html = html.decode('utf-8') # 设置编码,否则会乱码
22 # 根据得到的页面信息进行初步筛选过滤
23 final = [] # 初始化一个列表保存数据
24 bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象
25 body = bs.body
26 data = body.find('div', {'id': '7d'})
27 print(type(data))
28 ul = data.find('ul')
29 li = ul.find_all('li')
30 # 爬取自己需要的数据
31 i = 0 # 控制爬取的天数
32 lows = [] # 保存低温
33 highs = [] # 保存高温
34 daytimes = [] # 保存日期
35 weathers = [] # 保存天气
36 for day in li: # 便利找到的每一个li
37   if i < 7:
38     temp = [] # 临时存放每天的数据
39     date = day.find('h1').string # 得到日期
40     #print(date)
41     temp.append(date)
42     daytimes.append(date)
43     inf = day.find_all('p') # 遍历li下面的p标签 有多个p需要使用find_all 而不是find
44     #print(inf[0].string) # 提取第一个p标签的值,即天气
45     temp.append(inf[0].string)
46     weathers.append(inf[0].string)
47     temlow = inf[1].find('i').string # 最低气温
48     if inf[1].find('span') is None: # 天气预报可能没有最高气温
49       temhigh = None
50       temperate = temlow
51     else:
52       temhigh = inf[1].find('span').string # 最高气温
53       temhigh = temhigh.replace('', '')
54       temperate = temhigh + '/' + temlow
55     # temp.append(temhigh)
56     # temp.append(temlow)
57     lowStr = ""
58     lowStr = lowStr.join(temlow.string)
59     lows.append(int(lowStr[:-1])) # 以上三行将低温NavigableString转成int类型并存入低温列表
60     if temhigh is None:
61       highs.append(int(lowStr[:-1]))
62       highStr = ""
63       highStr = highStr.join(temhigh)
64       highs.append(int(highStr)) # 以上三行将高温NavigableString转成int类型并存入高温列表
65     temp.append(temperate)
66     final.append(temp)
67     i = i + 1
68 # 将最终的获取的天气写入csv文件
69 with open('weather.csv', 'a', errors='ignore', newline='') as f:
70   f_csv = csv.writer(f)
71   f_csv.writerows([cityname])
72   f_csv.writerows(final)
73 # 绘图
74 bar = pygal.Line() # 创建折线图
75 bar.add('最低气温', lows)
76 bar.add('最高气温', highs)
77 bar.x_labels = daytimes
78 bar.x_labels_major = daytimes[::30]
79 # bar.show_minor_x_labels = False # 不显示X轴最小刻度
80 bar.x_label_rotation = 45
81 bar.title = cityname+'未来七天气温走向图'
82 bar.x_title = '日期'
83 bar.y_title = '气温(摄氏度)'
84 bar.legend_at_bottom = True
85 bar.show_x_guides = False
86 bar.show_y_guides = True
87 bar.render_to_file('temperate.svg')

Python爬取天气数据实例扩展:

 1 import requests
 2 from bs4 import BeautifulSoup
 3 from pyecharts import Bar
 4 
 5 ALL_DATA = []
 6 def send_parse_urls(start_urls):
 7   headers = {
 8   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
 9   }
10   for start_url in start_urls:
11     response = requests.get(start_url,headers=headers)
12     # 编码问题的解决
13     response = response.text.encode("raw_unicode_escape").decode("utf-8")
14     soup = BeautifulSoup(response,"html5lib") #lxml解析器:性能比较好,html5lib:适合页面结构比较混乱的
15     div_tatall = soup.find("div",class_="conMidtab") #find() 找符合要求的第一个元素
16     tables = div_tatall.find_all("table") #find_all() 找到符合要求的所有元素的列表
17     for table in tables:
18       trs = table.find_all("tr")
19       info_trs = trs[2:]
20       for index,info_tr in enumerate(info_trs): # 枚举函数,可以获得索引
21         # print(index,info_tr)
22         # print("="*30)
23         city_td = info_tr.find_all("td")[0]
24         temp_td = info_tr.find_all("td")[6]
25         # if的判断的index的特殊情况应该在一般情况的后面,把之前的数据覆盖
26         if index==0:
27           city_td = info_tr.find_all("td")[1]
28           temp_td = info_tr.find_all("td")[7]
29         city=list(city_td.stripped_strings)[0]
30         temp=list(temp_td.stripped_strings)[0]
31         ALL_DATA.append({"city":city,"temp":temp})
32   return ALL_DATA
33 
34 def get_start_urls():
35   start_urls = [
36     "http://www.weather.com.cn/textFC/hb.shtml",
37     "http://www.weather.com.cn/textFC/db.shtml",
38     "http://www.weather.com.cn/textFC/hd.shtml",
39     "http://www.weather.com.cn/textFC/hz.shtml",
40     "http://www.weather.com.cn/textFC/hn.shtml",
41     "http://www.weather.com.cn/textFC/xb.shtml",
42     "http://www.weather.com.cn/textFC/xn.shtml",
43     "http://www.weather.com.cn/textFC/gat.shtml",
44   ]
45   return start_urls
46 
47 def main():
48   """
49   主程序逻辑
50   展示全国实时温度最低的十个城市气温排行榜的柱状图
51   """
52   # 1 获取所有起始url
53   start_urls = get_start_urls()
54   # 2 发送请求获取响应、解析页面
55   data = send_parse_urls(start_urls)
56   # print(data)
57   # 4 数据可视化
58     #1排序
59   data.sort(key=lambda data:int(data["temp"]))
60     #2切片,选择出温度最低的十个城市和温度值
61   show_data = data[:10]
62     #3分出城市和温度
63   city = list(map(lambda data:data["city"],show_data))
64   temp = list(map(lambda data:int(data["temp"]),show_data))
65     #4创建柱状图、生成目标图
66   chart = Bar("中国最低气温排行榜") #需要安装pyechart模块
67   chart.add("",city,temp)
68   chart.render("tempture.html")
69 
70 if __name__ == '__main__':
71   main()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM