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()
用python爬取15日气温并绘制气温折线图
最新推荐文章于 2023-03-15 19:59:57 发布