python爬取天氣數(shù)據(jù)的實(shí)例詳解
就在前幾天還是二十多度的舒適溫度,今天一下子就變成了個(gè)位數(shù),小編已經(jīng)感受到冬天寒風(fēng)的無(wú)情了。之前對(duì)獲取天氣都是數(shù)據(jù)上的搜集,做成了一個(gè)數(shù)據(jù)表后,對(duì)溫度變化的感知并不直觀。那么,我們能不能用python中的方法做一個(gè)天氣數(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+'未來(lái)七天氣溫走向圖' #設(shè)置圖形標(biāo)題
bar.x_title = '日期' #x軸標(biāo)題
bar.y_title = '氣溫(攝氏度)' # y軸標(biāo)題
bar.legend_at_bottom = True
bar.show_x_guides = False
bar.show_y_guides = True
bar.render_to_file('temperate1.svg') # 將圖像保存為SVG文件,可通過(guò)瀏覽器
最終生成的圖形如下圖所示,直觀的顯示了天氣情況:

完整代碼
import csv
import sys
import urllib.request
from bs4 import BeautifulSoup # 解析頁(yè)面模塊
import pygal
import cityinfo
cityname = input("請(qǐng)輸入你想要查詢天氣的城市:")
if cityname in cityinfo.city:
citycode = cityinfo.city[cityname]
else:
sys.exit()
url = '非常抱歉,網(wǎng)頁(yè)無(wú)法訪問(wèn)' + 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) # 制作請(qǐng)求
response = opener.open(request) # 得到應(yīng)答包
html = response.read() # 讀取應(yīng)答包
html = html.decode('utf-8') # 設(shè)置編碼,否則會(huì)亂碼
# 根據(jù)得到的頁(yè)面信息進(jìn)行初步篩選過(guò)濾
final = [] # 初始化一個(gè)列表保存數(shù)據(jù)
bs = BeautifulSoup(html, "html.parser") # 創(chuàng)建BeautifulSoup對(duì)象
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: # 便利找到的每一個(gè)li
if i < 7:
temp = [] # 臨時(shí)存放每天的數(shù)據(jù)
date = day.find('h1').string # 得到日期
#print(date)
temp.append(date)
daytimes.append(date)
inf = day.find_all('p') # 遍歷li下面的p標(biāo)簽 有多個(gè)p需要使用find_all 而不是find
#print(inf[0].string) # 提取第一個(gè)p標(biāo)簽的值,即天氣
temp.append(inf[0].string)
weathers.append(inf[0].string)
temlow = inf[1].find('i').string # 最低氣溫
if inf[1].find('span') is None: # 天氣預(yù)報(bào)可能沒(méi)有最高氣溫
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]))
highStr = ""
highStr = highStr.join(temhigh)
highs.append(int(highStr)) # 以上三行將高溫NavigableString轉(zhuǎn)成int類型并存入高溫列表
temp.append(temperate)
final.append(temp)
i = i + 1
# 將最終的獲取的天氣寫(xiě)入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+'未來(lái)七天氣溫走向圖'
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ù)實(shí)例擴(kuò)展:
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)
# 編碼問(wèn)題的解決
response = response.text.encode("raw_unicode_escape").decode("utf-8")
soup = BeautifulSoup(response,"html5lib") #lxml解析器:性能比較好,html5lib:適合頁(yè)面結(jié)構(gòu)比較混亂的
div_tatall = soup.find("div",class_="conMidtab") #find() 找符合要求的第一個(gè)元素
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): # 枚舉函數(shù),可以獲得索引
# print(index,info_tr)
# print("="*30)
city_td = info_tr.find_all("td")[0]
temp_td = info_tr.find_all("td")[6]
# if的判斷的index的特殊情況應(yīng)該在一般情況的后面,把之前的數(shù)據(jù)覆蓋
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():
"""
主程序邏輯
展示全國(guó)實(shí)時(shí)溫度最低的十個(gè)城市氣溫排行榜的柱狀圖
"""
# 1 獲取所有起始url
start_urls = get_start_urls()
# 2 發(fā)送請(qǐng)求獲取響應(yīng)、解析頁(yè)面
data = send_parse_urls(start_urls)
# print(data)
# 4 數(shù)據(jù)可視化
#1排序
data.sort(key=lambda data:int(data["temp"]))
#2切片,選擇出溫度最低的十個(gè)城市和溫度值
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創(chuàng)建柱狀圖、生成目標(biāo)圖
chart = Bar("中國(guó)最低氣溫排行榜") #需要安裝pyechart模塊
chart.add("",city,temp)
chart.render("tempture.html")
if __name__ == '__main__':
main()
到此這篇關(guān)于python爬取天氣數(shù)據(jù)的實(shí)例詳解的文章就介紹到這了,更多相關(guān)python爬蟲(chóng)天氣數(shù)據(jù)的分析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python題解LeetCode303區(qū)域和檢索示例詳解
這篇文章主要為大家介紹了python題解LeetCode303區(qū)域和檢索示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
python實(shí)現(xiàn)簡(jiǎn)易內(nèi)存監(jiān)控
這篇文章主要介紹了python實(shí)現(xiàn)簡(jiǎn)易內(nèi)存監(jiān)控,每隔3秒獲取系統(tǒng)內(nèi)存,當(dāng)內(nèi)存超過(guò)設(shè)定的警報(bào)值時(shí),獲取所有進(jìn)程占用內(nèi)存并發(fā)出警報(bào)聲,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
通過(guò)實(shí)例簡(jiǎn)單了解Python中yield的作用
這篇文章主要介紹了通過(guò)實(shí)例簡(jiǎn)單了解Python中yield的作用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
python SVM 線性分類模型的實(shí)現(xiàn)
這篇文章主要介紹了python SVM 線性分類模型的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
python 動(dòng)態(tài)繪制愛(ài)心的示例
這篇文章主要介紹了python 動(dòng)態(tài)繪制愛(ài)心的示例,幫助大家利用python繪制圖像,感興趣的朋友可以了解下2020-09-09
Python?sklearn庫(kù)中的隨機(jī)森林模型詳解
本文主要說(shuō)明?Python?的?sklearn?庫(kù)中的隨機(jī)森林模型的常用接口、屬性以及參數(shù)調(diào)優(yōu)說(shuō)明,需要讀者或多或少了解過(guò)sklearn庫(kù)和一些基本的機(jī)器學(xué)習(xí)知識(shí)2023-08-08
Python實(shí)現(xiàn)PPT幻燈片的添加、刪除或隱藏操作
PowerPoint文檔是商務(wù)、教育、創(chuàng)意等各領(lǐng)域常見(jiàn)的用于展示、教育和傳達(dá)信息的格式,在制作PPT演示文稿時(shí),靈活地操作幻燈片是提高演示效果、優(yōu)化內(nèi)容組織的關(guān)鍵步驟,本文給大家介紹了Python 操作PPT幻燈片- 添加、刪除、或隱藏幻燈片,需要的朋友可以參考下2024-08-08

