python將天氣預(yù)報(bào)可視化
前言
在想題材之際,打開(kāi)私信,有許多萌新&小伙伴詢(xún)問(wèn)我之前寫(xiě)的一篇《python爬取天氣預(yù)報(bào)數(shù)據(jù),并實(shí)現(xiàn)數(shù)據(jù)可視化》中的bug怎么解決,雖然我在之前,就在評(píng)論區(qū)提供了自己的解決思路,但可能不夠清楚,于是寫(xiě)這篇文章,來(lái)解決bug,并對(duì)程序進(jìn)行優(yōu)化。
結(jié)果展示
其中:
紅線(xiàn)代表當(dāng)天最高氣溫,藍(lán)線(xiàn)代表最低氣溫,最高氣溫點(diǎn)上的標(biāo)注為當(dāng)天的天氣情況。
如果使夜晚運(yùn)行程序,則最高氣溫和最低氣溫的點(diǎn)會(huì)重合,使由爬取數(shù)據(jù)產(chǎn)生誤差導(dǎo)致的。
程序代碼
詳細(xì)請(qǐng)看注釋
# -*- coding: UTF-8 -*- """ # @Time: 2022/1/4 11:02 # @Author: 遠(yuǎn)方的星 # @CSDN: https://blog.csdn.net/qq_44921056 """ import chardet import requests from lxml import etree from fake_useragent import UserAgent import pandas as pd from matplotlib import pyplot as plt # 隨機(jī)產(chǎn)生請(qǐng)求頭 ua = UserAgent(verify_ssl=False, path='D:/Pycharm/fake_useragent.json') # 隨機(jī)切換請(qǐng)求頭 def random_ua(): headers = { "user-agent": ua.random } return headers # 解析頁(yè)面 def res_text(url): res = requests.get(url=url, headers=random_ua()) res.encoding = chardet.detect(res.content)['encoding'] response = res.text html = etree.HTML(response) return html # 獲得未來(lái)七天及八到十五天的頁(yè)面鏈接 def get_url(url): html = res_text(url) url_7 = 'http://www.weather.com.cn/' + html.xpath('//*[@id="someDayNav"]/li[2]/a/@href')[0] url_8_15 = 'http://www.weather.com.cn/' + html.xpath('//*[@id="someDayNav"]/li[3]/a/@href')[0] # print(url_7) # print(url_8_15) return url_7, url_8_15 # 獲取未來(lái)七天的天氣情況 def get_data_7(url): html = res_text(url) list_s = html.xpath('//*[@id="7d"]/ul/li') # 獲取天氣數(shù)據(jù)列表 Date, Weather, Low, High = [], [], [], [] for i in range(len(list_s)): list_date = list_s[i].xpath('./h1/text()')[0] # 獲取日期,如:4日(明天) # print(list_data) list_weather = list_s[i].xpath('./p[1]/@title')[0] # 獲取天氣情況,如:小雨轉(zhuǎn)雨夾雪 # print(list_weather) tem_low = list_s[i].xpath('./p[2]/i/text()') # 獲取最低氣溫 tem_high = list_s[i].xpath('./p[2]/span/text()') # 獲取最高氣溫 if tem_high == []: # 遇到夜晚情況,篩掉當(dāng)天的最高氣溫 tem_high = tem_low # 無(wú)最高氣溫時(shí),使最高氣溫等于最低氣溫 tem_low = int(tem_low[0].replace('℃', '')) # 將氣溫?cái)?shù)據(jù)處理 tem_high = int(tem_high[0].replace('℃', '')) # print(type(tem_high)) Date.append(list_date), Weather.append(list_weather), Low.append(tem_low), High.append(tem_high) excel = pd.DataFrame() # 定義一個(gè)二維列表 excel['日期'] = Date excel['天氣'] = Weather excel['最低氣溫'] = Low excel['最高氣溫'] = High # print(excel) return excel def get_data_8_15(url): html = res_text(url) list_s = html.xpath('//*[@id="15d"]/ul/li') Date, Weather, Low, High = [], [], [], [] for i in range(len(list_s)): # data_s[0]是日期,如:周二(11日),data_s[1]是天氣情況,如:陰轉(zhuǎn)晴,data_s[2]是最低溫度,如:/-3℃ data_s = list_s[i].xpath('./span/text()') # print(data_s) date = modify_str(data_s[0]) # 獲取日期情況 weather = data_s[1] low = int(data_s[2].replace('/', '').replace('℃', '')) high = int(list_s[i].xpath('./span/em/text()')[0].replace('℃', '')) # print(date, weather, low, high) Date.append(date), Weather.append(weather), Low.append(low), High.append(high) # print(Date, Weather, Low, High) excel = pd.DataFrame() # 定義一個(gè)二維列表 excel['日期'] = Date excel['天氣'] = Weather excel['最低氣溫'] = Low excel['最高氣溫'] = High # print(excel) return excel # 將8-15天日期格式改成與未來(lái)7天一致 def modify_str(date): date_1 = date.split('(') date_2 = date_1[1].replace(')', '') date_result = date_2 + '(' + date_1[0] + ')' return date_result # 實(shí)現(xiàn)數(shù)據(jù)可視化 def get_image(date, weather, high, low): # 用來(lái)正常顯示中文標(biāo)簽 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用來(lái)正常顯示負(fù)號(hào) plt.rcParams['axes.unicode_minus'] = False # 根據(jù)數(shù)據(jù)繪制圖形 fig = plt.figure(dpi=128, figsize=(10, 6)) ax = fig.add_subplot(111) plt.plot(date, high, c='red', alpha=0.5, marker='*') plt.plot(date, low, c='blue', alpha=0.5, marker='o') # 給圖表中兩條折線(xiàn)中間的部分上色 plt.fill_between(date, high, low, facecolor='blue', alpha=0.2) # 設(shè)置圖表格式 plt.title('邳州近15天天氣預(yù)報(bào)', fontsize=24) plt.xlabel('日期', fontsize=12) # 繪制斜的標(biāo)簽,以免重疊 fig.autofmt_xdate() plt.ylabel('氣溫', fontsize=12) # 參數(shù)刻度線(xiàn)設(shè)置 plt.tick_params(axis='both', which='major', labelsize=10) # 修改刻度 plt.xticks(date[::1]) # 對(duì)點(diǎn)進(jìn)行標(biāo)注,在最高氣溫點(diǎn)處標(biāo)注當(dāng)天的天氣情況 for i in range(15): ax.annotate(weather[i], xy=(date[i], high[i])) # 顯示圖片 plt.show() def main(): base_url = 'http://www.weather.com.cn/weather1d/101190805.shtml' url_7, url_8_15 = get_url(base_url) data_1 = get_data_7(url_7) data_2 = get_data_8_15(url_8_15) data = pd.concat([data_1, data_2], axis=0, ignore_index=True) # ignore_index=True實(shí)現(xiàn)兩張表拼接,不保留原索引 get_image(data['日期'], data['天氣'], data['最高氣溫'], data['最低氣溫']) if __name__ == '__main__': main()
期望
這是以一個(gè)城市為例的可視化,下次爭(zhēng)取做到根據(jù)輸入的城市進(jìn)行天氣預(yù)報(bào)可視化
到此這篇關(guān)于python將天氣預(yù)報(bào)可視化的文章就介紹到這了,更多相關(guān)python天氣預(yù)報(bào)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)加密的方式總結(jié)
這篇文章主要介紹了python實(shí)現(xiàn)加密的方式總結(jié),文中給大家提到了python中加密的注意點(diǎn),通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01python實(shí)現(xiàn)連續(xù)變量最優(yōu)分箱詳解--CART算法
今天小編就為大家分享一篇python實(shí)現(xiàn)連續(xù)變量最優(yōu)分箱詳解--CART算法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11使用celery執(zhí)行Django串行異步任務(wù)的方法步驟
這篇文章主要介紹了使用celery執(zhí)行Django串行異步任務(wù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Django具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06Python爬蟲(chóng)獲取圖片并下載保存至本地的實(shí)例
今天小編就為大家分享一篇Python爬蟲(chóng)獲取圖片并下載保存至本地的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06python備份文件以及mysql數(shù)據(jù)庫(kù)的腳本代碼
最近正在學(xué)習(xí)python,看了幾天了,,所以寫(xiě)個(gè)小腳本練習(xí)練習(xí),沒(méi)什么含金量,只當(dāng)練手2013-06-06教你如何編寫(xiě)、保存與運(yùn)行Python程序的方法
這篇文章主要介紹了教你如何編寫(xiě)、保存與運(yùn)行Python程序的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python實(shí)現(xiàn)倉(cāng)庫(kù)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)倉(cāng)庫(kù)管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05