Python爬蟲爬取杭州24時溫度并展示操作示例
本文實例講述了Python爬蟲爬取杭州24時溫度并展示操作。分享給大家供大家參考,具體如下:
散點圖 爬蟲杭州今日24時溫度 https://www.baidutianqi.com/today/58457.htm
利用正則表達式爬取杭州溫度 面向?qū)ο缶幊? 圖表展示(散點圖 / 折線圖)導入相關(guān)庫
import requestsimport refrom matplotlib import pyplot as pltfrom matplotlib import font_managerimport matplotlib
類代碼部分
class Weather(object): def __init__(self): self.url = ’https://www.baidutianqi.com/today/58457.htm’ self.headers = {’user-agent’: ’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36’} #請求 def __to_requests(self): response = requests.get(url=self.url,headers=self.headers) return self.__to_paeser(response.content.decode(’utf-8’)) #解析 def __to_paeser(self,html): #正則表達式 要從數(shù)據(jù)循環(huán)的部分寫起 如果從循環(huán)的父標簽開始 , 則只會匹配到一個值 即父標簽下的某個標簽 , 而不是循環(huán)下的 pattern = re.compile(’<li>.*?<font class='red'>(.*?)</font>.*?<font class='blue'>(.*?)</font></li>’,re.S) return re.findall(pattern,html) #展示 def __to_show(self,data): x = [] y = [] for value in data: x.append(value[0]) y.append(int(value[1][-2:])) #畫布 plt.figure(figsize=(15,8),dpi=80) #中文 /System/Library/Fonts/PingFang.ttc C:WindowsFontssimsun.ttc my_font = font_manager.FontProperties(fname=’/System/Library/Fonts/PingFang.ttc’,size=18) #x y 軸刻度 標簽 區(qū)分 y的刻度值/刻度標簽 和 y本身的值 plt.xticks(fontproperties=my_font,rotation=60) y_ticks = ['{}℃'.format(i) for i in range(min(y),max(y)+1)] plt.yticks(range(min(y),max(y)+1),y_ticks,fontproperties=my_font,rotation=60) # x y 軸說明 plt.xlabel(’時間’,color=’orange’,rotation=60,fontproperties=my_font) plt.ylabel(’溫度’,color=’orange’,rotation=60,fontproperties=my_font) #網(wǎng)格 plt.grid(alpha=0.4) #標題 plt.title(’當天時刻溫度低值變化’,fontproperties=my_font) #圖例 plt.legend(prop=my_font) #作畫# plt.scatter(x,y,label=’2019-08-22’) plt.plot(x,y,color=’red’) plt.show() #操作 def to_run(self): result = self.__to_requests() self.__to_show(result)
調(diào)用并展示
if __name__ == ’__main__’: wt = Weather() wt.to_run()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章:
1. IntelliJ IDEA創(chuàng)建web項目的方法2. 存儲于xml中需要的HTML轉(zhuǎn)義代碼3. python numpy中setdiff1d的用法說明4. HTTP協(xié)議常用的請求頭和響應頭響應詳解說明(學習)5. python基礎(chǔ)之匿名函數(shù)詳解6. ASP中實現(xiàn)字符部位類似.NET里String對象的PadLeft和PadRight函數(shù)7. Python多線程實現(xiàn)支付模擬請求過程解析8. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容9. Python Request類源碼實現(xiàn)方法及原理解析10. python實現(xiàn)與redis交互操作詳解
