溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python爬蟲之天氣數(shù)據(jù)分析的示例

發(fā)布時間:2020-11-20 11:57:58 來源:億速云 閱讀:307 作者:小新 欄目:編程語言

這篇文章主要介紹python爬蟲之天氣數(shù)據(jù)分析的示例,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

使用pygal繪圖,使用該模塊前需先安裝pip install pygal,然后導(dǎo)入import pygal

bar = pygal.Line()  # 創(chuàng)建折線圖
bar.add('最低氣溫', lows)   #添加兩線的數(shù)據(jù)序列
bar.add('最高氣溫', highs)  #注意lows和highs是int型的列表
 
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
bar.x_label_rotation = 45
 
bar.title = cityname+'未來七天氣溫走向圖'   #設(shè)置圖形標題
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爬蟲之天氣數(shù)據(jù)分析的示例

 

完整代碼

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 = '非常抱歉,網(wǎng)頁無法訪問' + 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")  # 設(shè)置頭部信息
http_handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(http_handler)  # 修改頭部信息
opener.addheaders = [header]
request = urllib.request.Request(url)  # 制作請求
response = opener.open(request)  # 得到應(yīng)答包
html = response.read()  # 讀取應(yīng)答包
html = html.decode('utf-8')  # 設(shè)置編碼,否則會亂碼
 
# 根據(jù)得到的頁面信息進行初步篩選過濾
final = []  # 初始化一個列表保存數(shù)據(jù)
bs = BeautifulSoup(html, "html.parser")  # 創(chuàng)建BeautifulSoup對象
body = bs.body
data = body.find('div', {'id': '7d'})
print(type(data))
ul = data.find('ul')
li = ul.find_all('li')
 
# 爬取自己需要的數(shù)據(jù)
i = 0  # 控制爬取的天數(shù)
lows = []  # 保存低溫
highs = []  # 保存高溫
daytimes = []  # 保存日期
weathers = []  # 保存天氣
for day in li:  # 便利找到的每一個li
    if i < 7:
        temp = []  # 臨時存放每天的數(shù)據(jù)
        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:  # 天氣預(yù)報可能沒有最高氣溫
            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轉(zhuǎn)成int類型并存入低溫列表
        if temhigh is None:
            highs.append(int(lowStr[:-1]))
        else:
            highStr = ""
            highStr = highStr.join(temhigh)
            highs.append(int(highStr))  # 以上三行將高溫NavigableString轉(zhuǎn)成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()  # 創(chuàng)建折線圖
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爬蟲之天氣數(shù)據(jù)分析的示例的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI