1. 程式人生 > 實用技巧 >python爬蟲-資料視覺化-氣溫排行榜

python爬蟲-資料視覺化-氣溫排行榜

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理

以下文章來源於騰訊雲 作者:py3study

( 想要學習Python?Python學習交流群:1039649593,滿足你的需求,資料都已經上傳群檔案流,可以自行下載!還有海量最新2020python學習資料。 )

python爬蟲+資料視覺化專案(一)

  • 爬取目標:中國天氣網(起始url:http://www.weather.com.cn/textFC/hb.shtml#)
  • 爬取內容:全國實時溫度最低的十個城市氣溫排行榜
  • 使用工具:requests庫實現傳送請求、獲取響應。  
         beautifulsoup實現資料解析、提取和清洗  
         pyechart模組實現資料視覺化
  • 爬取結果:柱狀圖視覺化展示:

    直接放程式碼(詳細說明在註釋裡,歡迎同行相互交流、學習~):
1 import requests
 2 from bs4 import BeautifulSoup
 3 from pyecharts import Bar
 4 
 5 ALL_DATA = []
 6 def send_parse_urls(start_urls):
 7     headers = {
 8     "User-Agent": "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)"
 9     }
10     for
start_url in start_urls: 11 response = requests.get(start_url,headers=headers) 12 # 編碼問題的解決 13 response = response.text.encode("raw_unicode_escape").decode("utf-8") 14 soup = BeautifulSoup(response,"html5lib") #lxml解析器:效能比較好,html5lib:適合頁面結構比較混亂的 15 div_tatall = soup.find("
div",class_="conMidtab") #find() 找符合要求的第一個元素 16 tables = div_tatall.find_all("table") #find_all() 找到符合要求的所有元素的列表 17 for table in tables: 18 trs = table.find_all("tr") 19 info_trs = trs[2:] 20 for index,info_tr in enumerate(info_trs): # 列舉函式,可以獲得索引 21 # print(index,info_tr) 22 # print("="*30) 23 city_td = info_tr.find_all("td")[0] 24 temp_td = info_tr.find_all("td")[6] 25 # if的判斷的index的特殊情況應該在一般情況的後面,把之前的資料覆蓋 26 if index==0: 27 city_td = info_tr.find_all("td")[1] 28 temp_td = info_tr.find_all("td")[7] 29 city=list(city_td.stripped_strings)[0] 30 temp=list(temp_td.stripped_strings)[0] 31 ALL_DATA.append({"city":city,"temp":temp}) 32 return ALL_DATA 33 34 def get_start_urls(): 35 start_urls = [ 36 "http://www.weather.com.cn/textFC/hb.shtml", 37 "http://www.weather.com.cn/textFC/db.shtml", 38 "http://www.weather.com.cn/textFC/hd.shtml", 39 "http://www.weather.com.cn/textFC/hz.shtml", 40 "http://www.weather.com.cn/textFC/hn.shtml", 41 "http://www.weather.com.cn/textFC/xb.shtml", 42 "http://www.weather.com.cn/textFC/xn.shtml", 43 "http://www.weather.com.cn/textFC/gat.shtml", 44 ] 45 return start_urls 46 47 def main(): 48 """ 49 主程式邏輯 50 展示全國實時溫度最低的十個城市氣溫排行榜的柱狀圖 51 """ 52 # 1 獲取所有起始url 53 start_urls = get_start_urls() 54 # 2 傳送請求獲取響應、解析頁面 55 data = send_parse_urls(start_urls) 56 # print(data) 57 # 4 資料視覺化 58 #1排序 59 data.sort(key=lambda data:int(data["temp"])) 60 #2切片,選擇出溫度最低的十個城市和溫度值 61 show_data = data[:10] 62 #3分出城市和溫度 63 city = list(map(lambda data:data["city"],show_data)) 64 temp = list(map(lambda data:int(data["temp"]),show_data)) 65 #4建立柱狀圖、生成目標圖 66 chart = Bar("中國最低氣溫排行榜") #需要安裝pyechart模組 67 chart.add("",city,temp) 68 chart.render("tempture.html") 69 70 if __name__ == '__main__': 71 main()