準備:
Pycharm終端命令行或windows/Mac終端
1. requests(pip install requests)
2.BeautifulSoup(pip install beautifulsoup)
3.pyecharts(pip install pyecharts)
案例如下:
import requests
from bs4 import BeautifulSoup
from pyecharts.charts import Bar # 引入柱形圖
from pyecharts import options as opts
# 創建全局變量
ALL_DATA = []
'''
中國天氣網排名前十的最低氣溫數據可視化
'''
# 解析頁面
def parse_page(url):
# 請求頭
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36'
}
response = requests.get(url, headers=headers)
text = response.content.decode('utf-8')
'''
lxml:容錯性比較差,解析速度快(正規的網站)
html5lib:容錯性比較強,解析速度慢(不正規的網站)
'''
# 創建BeautifulSoup對象
soup = BeautifulSoup(text, 'html5lib') # 安裝:pip install html5lib
conMidtab = soup.find('div', class_='conMidtab')
# print(conMidtab) # 輸出請求的數據
tables = conMidtab.find_all('table') # 獲取所有的table
for tab in tables:
# 從第二個獲取tr標籤到結尾[2:]
trs = tab.find_all('tr')[2:] # 獲取所有tr標籤中的信息
for index, tr in enumerate(trs):
tds = tr.find_all('td') # 獲取所有的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]
# 把獲取的城市名稱與最低氣溫放到創建的空列表中
ALL_DATA.append({"city": city, "min_temp": int(min_temp)})
# print({"city": city, "temp": int(min_temp)}) # 輸出城市名稱和最低氣溫
# 主方法
def main():
# 地區
area = ['hb.shtml', 'db.shtml', 'hd.shtml', 'hz.shtml', 'hn.shtml', 'xb.shtml', 'xn.shtml', 'gat.shtml']
# 中國天氣網網址
base_url = 'http://www.weather.com.cn/textFC/'
for area in area:
url = base_url + area
parse_page(url)
# 最低氣溫進行排序
ALL_DATA.sort(key=lambda data: data['min_temp'])
# 獲取十個城市最低氣溫
data = ALL_DATA[0:10]
cities = list(map(lambda x: x['city'], data))
temps = list(map(lambda x: x['min_temp'], data))
bar = (
Bar()
.add_xaxis(cities) # X軸
.add_yaxis('', temps, is_selected=False, gap='80%') # Y軸,每個數據柱距離設置爲百分之80(距離可以隨意設置)
.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) # 不顯示數據柱頂部的數字
.set_global_opts(title_opts=opts.TitleOpts(title="中國天氣網最低排行榜")) # 柱形圖標題
)
bar.render("china_weather.html") # 數據保存到本地並可視化
# print(ALL_DATA) # 獲取城市與最低氣溫已經排序完畢的數據
# 測試方法
if __name__ == '__main__':
main()
pyecharts文檔:https://pyecharts.org/#/zh-cn/rectangular_charts
效果圖:
注意:隨着天氣的變化,柱形圖中的數據也隨之改變