初識python 之 爬蟲:爬取中國天氣網數據


用到模塊:

獲取網頁並解析:
import requests,html5lib
from bs4 import BeautifulSoup

使用pyecharts的Bar可視化工具“繪制圖表”,寫入HTML文件,附pyecharts官方中文API地址:https://pyecharts.org/#/
from pyecharts.charts import Bar

表格主題設置:
from pyecharts import options
from pyecharts.globals import ThemeType

獲取時間
from datetime import datetime

 

詳細代碼如下:  注:代碼中有使用到map函數,需要留意!

 

  1 #!/user/bin env python
  2 # author:Simple-Sir
  3 # time:2019/7/25 21:16
  4 # 爬取中國天氣網數據
  5 
  6 import requests,html5lib
  7 from bs4 import BeautifulSoup
  8 from pyecharts.charts import Bar  # 官方已取消 pyecharts.Bar 方式導入
  9 from pyecharts import options
 10 from pyecharts.globals import ThemeType
 11 from datetime import datetime
 12 
 13 WEARTHER_DATE =[]  # 城市天氣數據列表
 14 
 15 def urlText(url):
 16     '''
 17     獲取網頁HTML代碼,並解析成文本格式
 18     :param url: 網頁url地址
 19     :return: 解析之后的html文本
 20     '''
 21     headers = {
 22         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
 23     }
 24     respons = requests.get(url, headers=headers)  # 獲取網頁信息
 25     text = respons.content.decode('utf-8')  # 解析網頁
 26     return text
 27 
 28 def getDiv(url,area):
 29     '''
 30     獲取需要的html標簽:城市、最高溫度
 31     :param url:
 32     :param area: 區域:全國、全省(四川)  0:全國、其他任意值:全市
 33     :return:
 34     '''
 35     text = urlText(url)
 36     # soup = BeautifulSoup(text,'lxml') # 港澳台html中table標簽解析錯誤
 37     soup = BeautifulSoup(text, 'html5lib')  # html5lib 容錯性比lxml高
 38     conMidtab = soup.find_all('div',class_="conMidtab")[1]  # 獲取“明天”的天氣
 39     if area == '四川':
 40         # 獲取四川所有城市天氣
 41         trs = conMidtab.find_all('tr')[2:]
 42         for tr in trs:
 43             tds = tr.find_all('td')
 44             city_td = tds[0]
 45             city = list(city_td.stripped_strings)[0]  # 區縣
 46             temp_td = tds[-5]  # 倒數第5個td標簽
 47             temp = list(temp_td.stripped_strings)[0]  # 最高溫度
 48             print('正在獲取 {} 的最高氣溫:{}'.format(city, temp))
 49             WEARTHER_DATE.append({'城市': city, '最高溫度': int(temp)})
 50     else:
 51         # 獲取全國城市天氣
 52         tables = conMidtab.find_all('table')
 53         for t in tables:
 54             trs = t.find_all('tr')[2:]
 55             for index, tr in enumerate(trs):
 56                 tds = tr.find_all('td')
 57                 if index == 0:
 58                     city_td = tds[1]  # city_td = tds[-8]  # 港澳台格式錯誤
 59                 else:
 60                     city_td = tds[0]
 61                 city = list(city_td.stripped_strings)[0]  # 區縣
 62                 temp_td = tds[-5]  # 倒數第5個td標簽
 63                 temp = list(temp_td.stripped_strings)[0]  # 最高溫度
 64                 print('正在獲取 {} 的最高氣溫:{}'.format(city,temp))
 65                 WEARTHER_DATE.append({'城市': city, '最高溫度': int(temp)})
 66 
 67 
 68 # 可視化數據,對城市溫度排名
 69 # def getRownum(data):
 70 #     max_temp = data['最高溫度']  # 把列表里的每一項當作參數傳進來,再獲取“最高溫度”這一項的值
 71 #     return max_temp
 72 # WEARTHER_DATE.sort(key=getRownum)  # 功能和它一樣:WEARTHER_DATE.sort(key=lambda data:data['最高溫度'])
 73 
 74 def main():
 75     city_list =['hb','db','hd','hz','hn','xb','xn','gat','sichuan']
 76     getcity = input('您要獲取“全國”還是“四川”的最高溫度排名?\n')
 77     if getcity=='四川':
 78             url = 'http://www.weather.com.cn/textFC/{}.shtml'.format(city_list[-1])
 79             getDiv(url,getcity)
 80     else:
 81         for cl in city_list[:-1]:
 82             url = 'http://www.weather.com.cn/textFC/{}.shtml'.format(cl)
 83             getDiv(url,getcity)
 84     print('正在對天氣溫度進行排序處理...')
 85     WEARTHER_DATE.sort(key=lambda data: int(data['最高溫度']))  # 對列表中的字典數據排序,溫度從低到高
 86     WEARTHER_DATE.reverse()  # 把對列表反轉,溫度從高到低
 87     rownum = WEARTHER_DATE[:10]  # 獲取最高溫度排名前十的城市
 88     print('正在繪制圖表...')
 89     # 分別獲取城市、溫度列表
 90     # 原始方法:
 91     # citys=[]
 92     # temps=[]
 93     # for i in rownum:
 94     #     citys.append(i['城市'])
 95     #     temps.append(i['最高溫度'])
 96 
 97     # 高端方法:
 98     citys = list(map(lambda x: x['城市'], rownum))  # 使用map分離出城市
 99     temps = list(map(lambda x: x['最高溫度'], rownum))  # 使用map分離出最高溫度
100     # 通過使用pyecharts的Bar可視化數據,附官方中文API地址:https://pyecharts.org/#/
101     bar = Bar(init_opts = options.InitOpts(theme=ThemeType.DARK))  # 對表格添加主題
102     bar.add_xaxis(citys)
103     bar.add_yaxis('',temps)
104     tim = datetime.now().strftime('%Y-%m-%d')
105     bar.set_global_opts(title_opts={'text':'中國天氣網 {} 城市明日最高溫度排名前十({})'.format(getcity,tim)})
106     bar.render('中國天氣網城市最高溫度排名.html')
107     print('圖表繪制已完成,結果已寫入文件,請查看。')
108 if __name__ == '__main__':
109     main()
爬取中國天氣網數據

 

執行過程:

 

執行結果:

四川:

全國:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM