1. 程式人生 > 實用技巧 >關於Python爬取天氣資料的例項詳解內容

關於Python爬取天氣資料的例項詳解內容

前言

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯絡我們以作處理。

以下文章來源於Python自學指南

就在前幾天還是二十多度的舒適溫度,今天一下子就變成了個位數,小編已經感受到冬天寒風的無情了。之前對獲取天氣都是資料上的蒐集,做成了一個數據表後,對溫度變化的感知並不直觀。那麼,我們能不能用python中的方法做一個天氣資料分析的圖形,幫助我們更直接的看出天氣變化呢?

使用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檔案,可通過瀏覽器

最終生成的圖形如下圖所示,直觀的顯示了天氣情況:

完整程式碼

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('h1').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])) 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')

Python爬取天氣資料例項擴充套件:

import requests

from bs4 import BeautifulSoup

from pyecharts import Bar

 

ALL_DATA = []

def send_parse_urls(start_urls):

headers = {

"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"

}

for start_url in start_urls:

response = requests.get(start_url,headers=headers)

# 編碼問題的解決

response = response.text.encode("raw_unicode_escape").decode("utf-8")

soup = BeautifulSoup(response,"html5lib") #lxml解析器:效能比較好,html5lib:適合頁面結構比較混亂的

div_tatall = soup.find("div",class_="conMidtab") #find() 找符合要求的第一個元素

tables = div_tatall.find_all("table") #find_all() 找到符合要求的所有元素的列表

for table in tables:

trs = table.find_all("tr")

info_trs = trs[2:]

for index,info_tr in enumerate(info_trs): # 列舉函式,可以獲得索引

# print(index,info_tr)

# print("="*30)

city_td = info_tr.find_all("td")[0]

temp_td = info_tr.find_all("td")[6]

# if的判斷的index的特殊情況應該在一般情況的後面,把之前的資料覆蓋

if index==0:

city_td = info_tr.find_all("td")[1]

temp_td = info_tr.find_all("td")[7]

city=list(city_td.stripped_strings)[0]

temp=list(temp_td.stripped_strings)[0]

ALL_DATA.append({"city":city,"temp":temp})

return ALL_DATA

 

def get_start_urls():

start_urls = [

"http://www.weather.com.cn/textFC/hb.shtml",

"http://www.weather.com.cn/textFC/db.shtml",

"http://www.weather.com.cn/textFC/hd.shtml",

"http://www.weather.com.cn/textFC/hz.shtml",

"http://www.weather.com.cn/textFC/hn.shtml",

"http://www.weather.com.cn/textFC/xb.shtml",

"http://www.weather.com.cn/textFC/xn.shtml",

"http://www.weather.com.cn/textFC/gat.shtml",

]

return start_urls

 

def main():

"""

主程式邏輯

展示全國實時溫度最低的十個城市氣溫排行榜的柱狀圖

"""

# 1 獲取所有起始url

start_urls = get_start_urls()

# 2 傳送請求獲取響應、解析頁面

data = send_parse_urls(start_urls)

# print(data)

# 4 資料視覺化

#1排序

data.sort(key=lambda data:int(data["temp"]))

#2切片,選擇出溫度最低的十個城市和溫度值

show_data = data[:10]

#3分出城市和溫度

city = list(map(lambda data:data["city"],show_data))

temp = list(map(lambda data:int(data["temp"]),show_data))

#4建立柱狀圖、生成目標圖

chart = Bar("中國最低氣溫排行榜") #需要安裝pyechart模組

chart.add("",city,temp)

chart.render("tempture.html")

 

if __name__ == '__main__':

main()

到此這篇關於python爬取天氣資料的例項詳解的文章就介紹到這了