欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

python项目--bs4应用

时间:2023-04-25

#作者:shelbifrom bs4 import BeautifulSoupimport requestsfrom pyecharts import Bar #进行可视化 pyechartsALL_DATA = [] #定义一个空列表def parse_page(url): headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36' } response = requests.get(url , headers = headers) text = response.content.decode('utf-8') soup =BeautifulSoup(text , 'html5lib')#因为港澳台那页url网页程序并不规范 所以使用容错性更高的html5lib,但是速度比较 conMidtab = soup.find('div' , class_ = 'conMidtab') #慢 tables = conMidtab.find_all('table') #find_all其实是tag对象的方法,并不是属于beautifulsoup,所以可以直接通过tag for table in tables: #对象进行查询。所以conmidtab是tag对象, 所以可以直接.find_all查询 trs = table.find_all('tr')[2:] #[2:]:代表从第三个tr开始进行爬取,原因分析网页程序发现第一个第二个tr为表格的表头 for index , tr in enumerate(trs):#为什么要使用enumerate?因为分析网页程序发现除去华北地区,其他地区的第0个td信 tds = tr.find_all('td') #息都含有省份名称,所以抓取的时候会把省份名称抓取下来,而不是城市名称,所以当下 city_td = tds[0] #标为0的时候,即爬取的第一个td即第0个td取第一个td,分析网页程序过程中发现了第一 if index ==0: #个td含有城市名称 所以当下标index==0的时候取第一个td,即可以取到城市名称 city_td = tds[1] city = list(city_td.stripped_strings)[0]#stripped_strings将标签以及换行符去掉,留下文本 temp_td = tds[-2] min_temp = list(temp_td.stripped_strings)[0] ALL_DATA.append({"city":city , "min_temp":int(min_temp)})#将爬取到的城市以及其对应的最低温度以字典的形式添加到上述的空列表中 # print({"city":city , "min_temp":int(min_temp)})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:#将每个地方对应的url放进列表并且进行for in遍历成一个一个url分别进行解析 parse_page(url) ALL_DATA.sort(key=lambda data:data['min_temp'])#这块代码相当于把ALL_DATA这个列表赋给里面lambda的data,在取这列表 里头的min_temp值 data = ALL_DATA[0:10]#排序完之后取列表的前面十个元素即前面最冷的十个城市 citys = list(map(lambda x:x['city'] , data))#先遍历data的每一项传给x 此时x为列表,在取x中的city值,也就是data的 city值,结果返回给citys变量 temps = list(map(lambda x:x['min_temp'] , data)) chart = Bar("中国天气最低气温排行榜")#Bar柱状图的题目 chart.add('' , citys,temps) #第一个参数如下图1-1红色箭号显示的地方,第二个参数是x即横坐标,第三个参数是y即纵坐标 chart.render('temp.html') #没有路径 意味着本地文件,里头的字符串参数是文件名

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。