阅读文本大概须要 7 分钟。html
此次咱们的目标是爬取全国最冷的 10 座城市。html5
首先打开目标网站 - 中国天气网。bash
「 http://www.weather.com.cn/textFC/hb.shtml 」app
咱们要爬取全国全部城市的最低温度,而后获取温度最低的 10 个城市,并绘制成饼状图。echarts
因为爬取的数据少,考虑使用「 美味汤 - beautiful soup 」的方式来爬取。函数
另外,最后须要根据数据生成饼状图,须要安装「 pyecharts 」及兼容库,否则控制台会报错。网站
# 安装美味汤
pip3 install bs4
# html5lib 提高兼容性
pip3 install html5lib
# 安装图形库
pip3 install pyecharts
# 安装图形兼容库
pip3 install pyecharts-snapshot复制代码
注意:通常爬虫使用 lxml 去解析,可是因为中国天气网的「 港澳台 」页面源码中存在不少标签没有正确关闭,所以使用 html5lib 的方式去解析数据。ui
首先,咱们能够看到全国分为华北、东北、华东、华中、华南、西北、西南、港澳台,8 个区域来展现天气数据。url
# 一共8个区域,包含:华北、东北、华东、华中、华南、西北、西南、港澳台
# 华北
url_hb = 'http://www.weather.com.cn/textFC/hb.shtml'
# 东北
url_db = 'http://www.weather.com.cn/textFC/db.shtml'
# 华东
url_hd = 'http://www.weather.com.cn/textFC/hd.shtml'
# 华中
url_hz = 'http://www.weather.com.cn/textFC/hz.shtml'
# 华南
url_hn = 'http://www.weather.com.cn/textFC/hn.shtml'
# 西北
url_xb = 'http://www.weather.com.cn/textFC/xb.shtml'
# 西南
url_xn = 'http://www.weather.com.cn/textFC/xn.shtml'
# 港澳台【比较特殊】
url_gat = 'http://www.weather.com.cn/textFC/gat.shtml'
复制代码
咱们首先须要去获取每个区域下全部城市的天气数据,而后再对数据进行整理排序,写入到图形文件中。spa
首先爬取「 华北地区 」城市的天气数据。
能够获取到下面的规律:
全部的「 class=conMidtab 」的 6 个 div 保存着华北地区全部城市,包含今天之内将来一周的天气数据。
每个「 class=conMidtab2 」的 div 表明了一个省份的天气信息。
省份下面的城市天气数据,都包含 table 标签下。从第 3 个 tr 标签开始,是每个城市的天气数据。
soup = BeautifulSoup(text, 'html5lib')
div_conMidtab = soup.find('div', class_='conMidtab')
# 3.获取全部的table子Tag【天气信息都保存在table标签下面】
tables = div_conMidtab.find_all('table')
# 4.遍历片区下面的省份
for table in tables:
# 4.1过滤掉表头的两个tr数据
trs = table.find_all('tr')[2:]
# 5.遍历省份下面的市区
for index, tr in enumerate(trs):
tds = tr.find_all('td')
# 5.1 城市名称【第 1 个td标签】
# 注意:一个省份第一个城市取第 2 个td标签;其他城市取第 1 个td标签
city_td = tds[1] if index == 0 else tds[0]
city = list(city_td.stripped_strings)[0]
# 5.2 最低气温【倒数第 2 个td标签】
temp_low_td = tds[-2]
temp_low = list(temp_low_td.stripped_strings)[0]
ALL_DATA.append({"city": city, "temp_low": int(temp_low)})
复制代码
接下来,循环全国 8 个区域的列表,获取全部城市的名称和温度数据。
for index, url in enumerate(url_areas):
print('开始爬取第{}个区域'.format(index + 1))
parse_page(url)
time.sleep(1)
复制代码
而后拿到全部城市和温度的列表数据后,就能够对数据按温度进行「 升序 」排列。
def analysis_data():
""" 分析爬下来的数据 :return: """
# 1.默认的排序方式是升序【经过最低气温进行排序】
ALL_DATA.sort(key=lambda data: data['temp_low'])
# 2.获取前面10条数据
top_10 = ALL_DATA[:10]
return top_10
复制代码
最后,将数据写入到饼状图中。
def show_with_chart(top_10):
""" 10个城市和温度生成饼状图 :param top_10: :return: """
# 把列表tip_10中的每一项拿出去放到匿名函数中,而后组装成新的一个列表
# 1.获取城市列表
citys = list(map(lambda item: item['city'], top_10))
# 2.最低温度列表
temp_lows = list(map(lambda item: item['temp_low'], top_10))
# 3.生成饼状图并写入到html文件中
bar = Bar("最低气温排行榜")
bar.add("最低温度", citys, temp_lows)
# 渲染
bar.render('temperature.html')复制代码
最后打开生成的饼状图,就能很直观的查看到今天温度最低的 10 个城市。
本文首发于公众号「 AirPython 」,后台回复「好冷」便可获取完整代码。