初衷
十一回家走访亲戚,家长们聊关于附近工厂的事情。笔者家附近有一个清洁能源厂,同时还有一个水库,这种复杂的空气对流,夏季容易遭受冰雹的侵害。
以水果谋生的农户,躲得过人祸,免不了天灾。笔者暗想,用一定的大数据分析,证明这两种存在对当地的影响。
于是有了此文。
代码
网上相关资源很多,笔者习惯在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,网站已经作了区分,所以不必担心。
统计分析结果出来后,再续。