溫馨提示×

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

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

Python如何爬取杭州24時(shí)溫度并展示

發(fā)布時(shí)間:2021-06-18 09:25:55 來(lái)源:億速云 閱讀:166 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)Python如何爬取杭州24時(shí)溫度并展示的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來(lái)看看吧。

散點(diǎn)圖 爬蟲杭州今日24時(shí)溫度 https://www.baidutianqi.com/today/58457.htm

  1. 利用正則表達(dá)式爬取杭州溫度

  2. 面向?qū)ο缶幊?/p>

  3. 圖表展示(散點(diǎn)圖 / 折線圖)

導(dǎo)入相關(guān)庫(kù)

import requests
import re
from matplotlib import pyplot as plt
from matplotlib import font_manager
import 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)的部分寫起 如果從循環(huán)的父標(biāo)簽開始 , 則只會(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:]))
    #畫布
    plt.figure(figsize=(15,8),dpi=80)
    #中文 /System/Library/Fonts/PingFang.ttc   C:\Windows\Fonts\simsun.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 軸說明
    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)
    #作畫
#     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()

Python如何爬取杭州24時(shí)溫度并展示
Python如何爬取杭州24時(shí)溫度并展示

感謝各位的閱讀!關(guān)于“Python如何爬取杭州24時(shí)溫度并展示”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

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

AI