python爬取歷史天氣
阿新 • • 發佈:2018-11-10
初衷
十一回家走訪親戚,家長們聊關於附近工廠的事情。筆者家附近有一個清潔能源廠,同時還有一個水庫,這種複雜的空氣對流,夏季容易遭受冰雹的侵害。
以水果謀生的農戶,躲得過人禍,免不了天災。筆者暗想,用一定的大資料分析,證明這兩種存在對當地的影響。
於是有了此文。
程式碼
網上相關資源很多,筆者習慣在python抓資料,而將分析留給matlab,檔案修改一類交給C++。
以下程式碼小作修改,原始連結 Python3獲取歷史天氣資料
import requests from bs4 import BeautifulSoup import pandas as pd import time # 引數city為城市拼音,*years為年份引數(int型別),若只傳入一個數字則只爬取對應年份資料,若輸入多個年份則預設以第一個年份為起始年,最後一個年份為終止年(例如傳入2011,2018,則爬取2011到2018年天氣資料),目前最久遠的天氣資料只有2011年的 來源:[Python3獲取歷史天氣資料](https://blog.csdn.net/weixin_39671140/article/details/82716619) 該程式將城市拼音輸入,直接修改為查詢天氣的連結。 def get_weather_historic_data(city, *years): res = [] for year in range(years[0], years[-1] + 1): print('正在獲取%d年資料...' % (year)) for month in range(1, 13): if month < 10: response = requests.get('http://lishi.tianqi.com/%s/%d0%d.html' % (city, year, month)).text else: response = requests.get('http://lishi.tianqi.com/%s/%d%d.html' % (city, year, month)).text soup = BeautifulSoup(response, "html.parser") # 檢查是否找到該時段天氣資料,沒有則跳到下個月 try: ul = soup.find('div', class_='tqtongji2').find_all('ul') except: continue # columns作為DataFrame物件的列名 columns = ul[0].get_text().split() for i in range(1, len(ul)): res.append(ul[i].get_text().split()) # 返回pandas中的dataframe資料型別 return pd.DataFrame(res, columns=columns) st = time.time() # shenzhen指的是深圳,2011是起始年份,2018是終止年份,即爬取2011到2018年深圳天氣資料 df = get_weather_historic_data('dali', 2012, 2018) # 儲存成本地excel檔案 #你想要儲存檔案的位置 df.to_excel(r'D:\Cat_Dog_CNN\深圳歷史天氣資料.xlsx') print('完成,用時', round(time.time() - st, 3), 's')
分析網頁
歷史天氣網站介面如下:
根據拼音,可以到達感興趣的城市網站。
同名城市
筆者所處小縣城為陝西大荔,而更著名的是雲南大理,筆者分析了一下網站連結,發現在大荔拼音正常,而云南大理,在url處為dali1,網站已經作了區分,所以不必擔心。
統計分析結果出來後,再續。