Python3获取历史天气数据

3 篇文章 0 订阅
2 篇文章 0 订阅

数据来源是历史天气网

网址:http://lishi.tianqi.com/

函数输入的是城市拼音,年份(可设置起始年份),输出的是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')

 

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值