Python3獲取歷史天氣資料

2021-08-28 03:45:59 字數 1465 閱讀 4106

資料**是歷史天氣網

**:函式輸入的是城市拼音,年份(可設定起始年份),輸出的是pandas裡的dataframe資料型別,便於儲存成excel或其他本地資料儲存形式。

# -*- coding: utf-8 -*-

"""created on sat sep 15 11:20:40 2018

@author: csm

"""import requests

from bs4 import beautifulsoup

import pandas as pd

import time

#引數city為城市拼音,*years為年份引數(int型別),若只傳入乙個數字則只爬取對應年份資料,若輸入多個年份則預設以第乙個年份為起始年,最後乙個年份為終止年(例如傳入2011,2018,則爬取2011到2023年天氣資料),目前最久遠的天氣資料只有2023年的

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('%s/%d0%d.html' %(city,year,month)).text

else:

response = requests.get('%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)):

#返回pandas中的dataframe資料型別

return pd.dataframe(res,columns = columns)

st = time.time()

#shenzhen指的是深圳,2011是起始年份,2018是終止年份,即爬取2011到2023年深圳天氣資料

df = get_weather_historic_data('shenzhen',2011,2018)

#儲存成本地excel檔案

#df.to_excel(r'd:\歷史天氣資料.xlsx')

print('完成,用時',round(time.time()-st,3),'s')

python爬取歷史天氣資料

import requests from requests.exceptions import requestexception from bs4 import beautifulsoup import os import csv import time def get one page url 獲...

Python 爬蟲,爬取歷史天氣資料

先上原始碼 這次用的是beautifulsoup,解析html,非常的便捷 import datetime import pandas as pd import re import requests import time from bs4 import beautifulsoup headers ...

python獲取城市天氣資料案例

最近對城市的空氣質素指數尤為關心,總是想對比一下各個城市的空氣質素,單個查太麻煩,於是想到來用python 來獲取 注意 以下 需要在pyton2中執行 coding utf 8 import urllib2 import time citys 北京 天津 石家莊 太原 西安 重慶 成都 貴陽 上海...