2.3 实验结果

文章插图
注:5月25日的数据(以实战当天为准)
三、源代码用函数进行封装
import requestsimport pandas as pdfrom bs4 import BeautifulSoupfrom fake_useragent import UserAgentfrom lxml import etreeimport matplotlib.pyplot as plt'''爬取中国天气网的温度数据并汇总画出温度最高前10名的数据展示图画出温度最低前10名的数据展示图'''headers = {"user-agent": UserAgent().random}HIGH_DATA = https://www.isolves.com/it/cxkf/yy/Python/2020-08-05/[]LOW_DATA = []# 使用bs4库的BeautifSoup对象来获取最高温度的数据,使用HIGH_DATA来存放数据def get_high_temperature(url):response = requests.get(url, headers=headers)text = response.content.decode("utf-8")soup = BeautifulSoup(text,'html5lib')conMidtab = soup.find('div',class_='conMidtab')tables = conMidtab.find_all('table')for table in tables:trs = table.find_all('tr')[2:]for index,tr in enumerate(trs):# ebumerate能够取出对应的下标和值tds = tr.find_all('td')if index == 0:city_td = tds[1]else:city_td = tds[0]city = list(city_td.stripped_strings)[0]temp_td = tds[-5]max_temp = list(temp_td.stripped_strings)[0]HIGH_DATA.append({"city": city, 'high_temp': int(max_temp)})# 使用lxml库的xpath方法来获取最低温度的数据,使用LOW_DATA来存储数据def get_low_temperature(url):response = requests.get(url, headers=headers)text = response.text.encode('ISO-8859-1')trees = etree.HTML(text)citys = trees.xpath('//div[@class="hanml"]/div[1]//td[@width="83"][@height="23"]/a/text()')lows = trees.xpath('//div[@class="hanml"]/div[1]//td[@width="86"]/text()')while True:if '最低气温' not in lows:breakelse:lows.remove('最低气温')for i in zip(citys, lows):city, low = iLOW_DATA.append({"city": city, "low_temp": int(low)})# 使用pandas来格式化数据,使用matplotlib.pyplot 画图def draw_picture(LOW,HIGH):i = pd.DataFrame(LOW)j = pd.DataFrame(HIGH)# 分区域绘图subplot(行,列,第()个)plt.subplot(2, 1, 1)# 逆序排序取前面十个然后放在ten_low中ten_low = i.sort_values(by="low_temp", ascending=True)[0:10]# 设置x和y轴的字体为黑体(SimHei)/解决轴不能显示字体的问题plt.rcParams['font.sans-serif'] = ['SimHei']# 解决不能显示负号的问题plt.rcParams['axes.unicode_minus'] = False# 取出ten_low中的城市和气温x1 = list(ten_low['city'])y1 = list(ten_low['low_temp'])# 画出bar图plt.bar(x1, y1)# 定义x和y轴的名称plt.xlabel('城市', fontproperties='SimHei')plt.ylabel("温度", fontproperties='SimHei')# 定义图表的名称plt.title("中国各个城市的今日温度最低前十名", fontproperties='SimHei')# 显示bar图上的数值for x, y in zip(x1, y1):plt.text(x, y, '%s' % y, ha='center', va='bottom')# 画出第二个子图plt.subplot(2, 1, 2)# 取出最低气温的后面十个数值ten_high = j.sort_values(by="high_temp", ascending=True)[-10:]x2 = list(ten_high['city'])y2 = list(ten_high['high_temp'])# plt.rcParams['font.sans-serif'] = ['SimHei']# plt.rcParams['axes.unicode_minus'] = Falseplt.bar(x2, y2)plt.xlabel('城市', fontproperties='SimHei')plt.ylabel("温度", fontproperties='SimHei')plt.title("中国各个城市的今日温度最高前十名", fontproperties='SimHei')for x, y in zip(x2, y2):plt.text(x, y, '%s' % y, ha='center', va='bottom')# 调整每隔子图之间的距离(默认)plt.tight_layout()plt.show()def main():zone = ['db', 'hb', 'hd', 'hz', 'hn', 'xb', 'xn', 'gat']for z in zone:url = "http://www.weather.com.cn/textFC/{}.shtml".format(z)get_high_temperature(url)get_low_temperature(url)draw_picture(LOW_DATA,HIGH_DATA)if __name__ == '__main__':main()写在最后在实战出现l什么问题可以随时留言告诉小编,另外附加一个bug,在每天晚上中国天气网当天的最高气温可能会发生变化,数据会被清除变成‘-’,导致实验失败,注意自己的实战时间
文章插图
我发现湖南长沙这边才是最热的 一个南方城市 居然能达到39 40 ° 太可怕了呀 对了 源码获取记得加后台私信小编 源码 获取
推荐阅读
- Python小程序网络耗时监控
- 你知道Python有内置数据库吗?Python内置库SQlite3使用指南
- Python基础算法之快速求解
- 数据科学家必须知道的前十大PYTHON库
- Python编程语言的核心是什么?
- Python安装库太慢?配置好这个速度飞起
- 不可不知的Python数据结构
- 5分钟内搭建你的第一个Python聊天机器人
- 深度详解Python中Unicode编码
- 通过 VSCode RTOS 插件使用 Python 为物联网系统编写程序
