每天进步一点点,五年之后大不同。
import requests
from bs4 import BeautifulSoup
from pyecharts.charts import Bar #没有在各个包需要在python里面下载:pip install pyecharts
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
}
ALL_DATA = [] #创建空列表用来 存储最终的结果
def parse_page(url):
req = requests.get(url,headers=headers)
text = req.content.decode('utf-8') #获取的是字符串
#decode bytes -> str #字节转换为字符串
#encode str ->bytes #字符串转换为字节
#pip install html5lib #安装html5lib解析器
soup = BeautifulSoup(text,'html5lib') #html5lib和lxml均为解析器
conMidtab = soup.find('div',class_='conMidtab') #查找第一个符合要求的标签用find
# conMidtab = soup.find('div',attrs={'class':'conMidtab'})
tables = conMidtab.find_all('table') #返回的是一个列表,查找所有符合的标签用find_all
for table in tables:
trs = table.find_all('tr')[2:] #从第三个tr标签开始查找所有,不同于xpath的谓词是从1开始的
# for tr in trs:
# tds = tr.find_all('td')
# city_td = tds[0] #标签+城市名称
# city = list(city_td.stripped_strings)[0] #只留城市名称,需要先将city_td.stripped_strings转换为列表
for index,tr in enumerate(trs): #index为下标,enumerate的用法,生成值对应的下标
tds = tr.find_all('td')
city_td = tds[0]
# print(city_td,index)
if index == 0:
city_td = tds[1]
city = list(city_td.stripped_strings)[0]
temp_td = tds[-5] #取倒数第五个
temp = list(temp_td.stripped_strings)[0]
ALL_DATA.append( {'city':city,'temp':temp}) #向ALL_DATA空列表中追加数据
def main():
urls = [
"http://www.weather.com.cn/textFC/hb.shtml", #华北
"http://www.weather.com.cn/textFC/db.shtml", #东北
"http://www.weather.com.cn/textFC/hd.shtml", #华东
"http://www.weather.com.cn/textFC/hz.shtml", #华中
"http://www.weather.com.cn/textFC/hn.shtml", #华南
"http://www.weather.com.cn/textFC/xb.shtml", #西北
"http://www.weather.com.cn/textFC/xn.shtml", #西南
"http://www.weather.com.cn/textFC/gat.shtml", #港澳台
]
for url in urls:
parse_page(url) #给上面的parse_page函数传值
ALL_DATA.sort(key=lambda x:x['temp'],reverse=True) #将temp(最高气温)从小到大进行排序
data = ALL_DATA[0:15] #取前15个
city_list = list(map(lambda x:x['city'],data))
temp_list = list(map(lambda x:x['temp'],data))
bar = Bar() # 安装导入成功以后实例化一个对象
bar.add_xaxis(city_list) #给横坐标赋值
bar.add_yaxis("最高气温",temp_list) #给纵坐标赋值
bar.render('十五城市最高气温.html') #生成文件
if __name__ == '__main__':
main()
# ALL_DATA = [
# {'city': '北京', 'temp': '29'},
# {'city': '海淀', 'temp': '31'},
# {'city': '朝阳', 'temp': '32'},
# {'city': '顺义', 'temp': '29'},
# {'city': '怀柔', 'temp': '35'}
# ]
# ALL_DATA.sort(key=lambda x:x['temp'])
# print(ALL_DATA[0:2])
万水千山总是情,点个关注行不行。
你的一个小小举动,将是我分享更多干货的动力。
我的博客都是上下具有连贯性的,只看一篇可能不太懂,需要多篇结合在一起才能真正看懂,我是学习python的小颜,希望大家点个关注,一起沟通学习哦。