用python爬取15日气温并绘制气温折线图

import urllib
import urllib.request
import re
import matplotlib.pyplot as plt
import datetime
import matplotlib as mpl
dates = []
temperature = []
def getpage(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent')    #添加自己的用户代理
    data = urllib.request.urlopen(req).read().decode("utf-8")
    return data

def getTem(data):
    regex = '<div>(.*?)℃</div>'
    p = re.compile(regex)
    temp = p.findall(data)
    temperature.append(temp)
    return temperature

def convert(temperature):
    tempSplit = []
    lowtemp = []
    hightemp = []
    for temp in temperature[0]:
        tempSplit.append(temp.split('/'))
    for t in tempSplit:
        lowtemp.append(int(t[0]))
        hightemp.append(int(t[1]))
    return lowtemp, hightemp

if __name__=="__main__":
    url = "https://tianqi.so.com/weather/101120201"
    temperature = getTem(getpage(url))
    lowtemp, hightemp = convert(temperature)
    starttime = datetime.datetime(2020, 5, 25)
    endtime = datetime.datetime(2020, 6, 9)
    interval = datetime.timedelta(days=1)  # 时间间隔
    dates = mpl.dates.drange(starttime, endtime, interval)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot_date(dates, lowtemp, 'o-', label="最低气温", linewidth=3, markersize=10)
    for x, y in zip(dates, lowtemp):
        plt.text(x, y, str(y)+"℃", fontsize=15)
    ax.plot_date(dates, hightemp, 'o-', color='r', label="最高气温", linewidth=3, markersize=10)
    for x, y in zip(dates, hightemp):
        plt.text(x, y, str(y)+"℃", fontsize=15)
    plt.fill_between(dates, hightemp, lowtemp, facecolor="blue", alpha=0.2)
    fig.autofmt_xdate()
    plt.legend()
    plt.title("15日天气气温状况", fontsize=20)
    plt.xlabel("日期", fontsize=20)
    plt.ylabel("温度", fontsize=20)
    plt.tick_params(labelsize=15)
    mpl.rcParams["font.sans-serif"] = ["KaiTi"]
    mpl.rcParams["axes.unicode_minus"] = False
    plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值