数据来源是历史天气网
函数输入的是城市拼音,年份(可设置起始年份),输出的是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到2018年天气数据),目前最久远的天气数据只有2011年的
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('shenzhen',2011,2018)
#保存成本地excel文件
#df.to_excel(r'D:\历史天气数据.xlsx')
print('完成,用时',round(time.time()-st,3),'s')