Python爬蟲(chóng)爬取杭州24時(shí)溫度并展示操作示例
本文實(shí)例講述了Python爬蟲(chóng)爬取杭州24時(shí)溫度并展示操作。分享給大家供大家參考,具體如下:
散點(diǎn)圖 爬蟲(chóng)杭州今日24時(shí)溫度 https://www.baidutianqi.com/today/58457.htm
利用正則表達(dá)式爬取杭州溫度 面向?qū)ο缶幊? 圖表展示(散點(diǎn)圖 / 折線圖)導(dǎo)入相關(guān)庫(kù)
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’} #請(qǐng)求 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): #正則表達(dá)式 要從數(shù)據(jù)循環(huán)的部分寫(xiě)起 如果從循環(huán)的父標(biāo)簽開(kāi)始 , 則只會(huì)匹配到一個(gè)值 即父標(biāo)簽下的某個(gè)標(biāo)簽 , 而不是循環(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:])) #畫(huà)布 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 軸刻度 標(biāo)簽 區(qū)分 y的刻度值/刻度標(biāo)簽 和 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 軸說(shuō)明 plt.xlabel(’時(shí)間’,color=’orange’,rotation=60,fontproperties=my_font) plt.ylabel(’溫度’,color=’orange’,rotation=60,fontproperties=my_font) #網(wǎng)格 plt.grid(alpha=0.4) #標(biāo)題 plt.title(’當(dāng)天時(shí)刻溫度低值變化’,fontproperties=my_font) #圖例 plt.legend(prop=my_font) #作畫(huà)# 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正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟2. UDDI FAQs3. IntelliJ IDEA設(shè)置編碼格式的方法4. idea設(shè)置代碼格式化的方法步驟5. IntelliJ IDEA設(shè)置條件斷點(diǎn)的方法步驟6. PHP腳本的10個(gè)技巧(8)7. XML入門精解之結(jié)構(gòu)與語(yǔ)法8. java實(shí)現(xiàn)2048小游戲(含注釋)9. idea重置默認(rèn)配置的方法步驟10. python中復(fù)數(shù)的共軛復(fù)數(shù)知識(shí)點(diǎn)總結(jié)
