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