【Python3 爬虫】U14_爬取中国天气网
生活随笔
收集整理的這篇文章主要介紹了
【Python3 爬虫】U14_爬取中国天气网
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄1.網頁分析2.代碼實現
1.網頁分析
庚子年初,各種大事件不期而至,又趕上最近氣溫突變,所以寫個爬蟲來爬取下中國天氣網,并通過圖表反映氣溫最低的前20個城市。
中國天氣網:http://www.weather.com.cn/textFC/hb.shtml
打開后如下圖:
從圖中可以看到所有城市按照地區劃分了,并且每個城市都有最低氣溫和最高氣溫,通過chrome查看Elements,如下:
從上圖可以看到展示當天的數據,那么<div class='conMidtab'>..這個標簽則沒有style="display:none;"屬性。
那么,具體的每一行數據又存在哪里呢?
從上圖可以看出,數據存儲在<table>標簽下的<tr>標簽中,通過下圖可以看到,tr標簽下的td標簽就可以找到每個城市的最低氣溫了`。
2.代碼實現
實現以下代碼需要安裝的庫:
pip install requests
pip install bs4
pip install html5lib
pip install pyecharts
官方文檔(pyecharts1.7.x)https://gallery.pyecharts.org/
具體代碼如下:
# Author:Logan
# Date:2020/3/31 16:28
# IDE:PyCharm
import requests
from bs4 import BeautifulSoup
from pyecharts.charts import Line,Bar
import pyecharts.options as opts
DATA_TEMP = []
HEADERS = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
def parse_page(url):
response = requests.get(url, headers=HEADERS)
html_str = response.content.decode('utf-8')
# html5lib容錯性比較高
soup = BeautifulSoup(html_str,'html5lib')
divs = soup.find('div',class_='conMidtab')
tables = divs.find_all('table')
for table in tables:
trs = table.find_all('tr')[2:]
for index,tr in enumerate(trs):
tds = tr.find_all('td')
# 城市獲取
city_td = tds[0]
if index == 0:
city_td = tds[1]
city = list(city_td.stripped_strings)[0]
# 最低氣溫獲取
temp_td = tds[-2]
min_temp = list(temp_td.stripped_strings)[0]
DATA_TEMP.append({"city":city,"min_temp":min_temp})
print({"city":city,"min_temp":min_temp})
def show_line_chart(data):
DATA_TEMP=data
DATA_TEMP.sort(key=lambda data: data['min_temp'])
show_data = DATA_TEMP[0:10] # 氣溫最低的前10個城市
cities = list(map(lambda x: x['city'], show_data))
min_temp = list(map(lambda x: x['min_temp'], show_data))
# 展示為折線圖與柱狀圖
(
Bar(init_opts=opts.InitOpts(width="1000px", height="350px"))
.add_xaxis(cities)
.add_yaxis("最低氣溫", min_temp)
.set_global_opts(
title_opts=opts.TitleOpts(title="今日全國氣溫最低的前10個城市", subtitle="柱狀圖"),
yaxis_opts=opts.AxisOpts(name="城市"),
xaxis_opts=opts.AxisOpts(name="最低氣溫"),
)
.render("temperature_line_chart.html")
)
def main():
base_url = 'http://www.weather.com.cn/textFC/{}.shtml'
# 構造url
name_list = ['hb','db','hd','hz','hn','xb','xn','gat']
for name in name_list:
url = base_url.format(name)
parse_page(url)
# 分析數據
show_line_chart(DATA_TEMP)
if __name__ == '__main__':
main()
代碼運行后,則生成了temperature_line_chart.html,在瀏覽器打開可以看到生成的柱狀圖如下。
總結
以上是生活随笔為你收集整理的【Python3 爬虫】U14_爬取中国天气网的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 向【KaliLinux】虚拟机无法复制粘
- 下一篇: 推荐:网络求职助手