當前位置:首頁 > IT技術(shù) > 編程語言 > 正文

python 爬蟲可視化,天氣
2022-04-19 11:22:41

網(wǎng)站地址='https://lishi.tianqi.com/chengdu/201704'

import matplotlib.pyplot as plt
import requests
from lxml import etree
from numpy import *
import re
if __name__ == '__main__':
    k = []
    l = []
    for i in range(21,22):
        for j in range(1,13):
            if j<10:
                url = "https://lishi.tianqi.com/chengdu/20%s0%s.html"%(i,j)
                headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36 Edg/100.0.1185.29'}
                res = requests.get(url,headers=headers)
                res.encoding = res.apparent_encoding
                tree = etree.HTML(res.text)
                es = tree.xpath('//ul[@class="thrui"]/li/div/text()')#溫度
                a=es[1:-1:5]#最高氣溫,用切片
                b=es[2:-1:5]#最低氣溫,用切片
                # 1.將score_list列表轉(zhuǎn)換為以“,”為分隔符的字符串
                list_string = ",".join(a)
                # 2.使用re模塊下的方法——findall對name_score_list_string進行正則匹配,提取出所有的數(shù)值型字符串
                score_list = re.findall(r"d+", list_string)
                # 3.將得到的score_list中的元素轉(zhuǎn)換為int型
                list_int = list(map(int, score_list))
                f = mean(list_int)#求平均數(shù)
                f1=round(f,0)

                ist=",".join(b)
                score_lis =re.findall(r"d+",ist)
                list_in =list(map(int,score_lis))
                g=mean(list_in)
                g1=round(g,0)
                k.append(int(f1))
                l.append(int(g1))
    x1 = range(1, 10)
    x2 = range(1, 10)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 顯示中文標簽
    plt.rcParams['axes.unicode_minus'] = False
    plt.plot(x1, k, label='最高溫度', linewidth=3, color='r', marker='o',
                markerfacecolor='blue', markersize=12)
    plt.plot(x1, l, label='最低溫度')
    plt.xlabel('月份')
    plt.ylabel('氣溫')
                # 添加圖形標題
    plt.title('每月平均最高氣溫波動趨勢')
    plt.legend()
    # 顯示圖形
    plt.show()

?

本文摘自 :https://www.cnblogs.com/

開通會員,享受整站包年服務(wù)立即開通 >