python爬虫天气预报难不难_python爬虫可以用来看天气预报吗?
就在前幾天,溫度就下降的很厲害,出門不多穿衣服,被風(fēng)吹的酸爽大家都體驗(yàn)過。小編不知道小伙伴們有沒有看天氣預(yù)報(bào)的習(xí)慣,沒有的話可以從本期的代碼開始,要不要自己做一個(gè)天氣預(yù)報(bào)表呢~在開始做表之前,我們肯定要準(zhǔn)備一些數(shù)據(jù)和操作工具的,下面就一起來做天氣預(yù)報(bào)表吧。
1 構(gòu)造URL列表
每個(gè)月份的歷史天氣數(shù)據(jù)是通過一個(gè) Javascript 文件獲取的。因此,我們需要構(gòu)造帶爬取數(shù)據(jù)的 URL 列表,再批量爬取數(shù)據(jù)。#?構(gòu)造2019全年的月份列表
months?=?[]
for?year?in?(2019,):
for?month?in?range(12):
months.append("%dd"%(year,?month 1))
todo_urls?=?[
"http://tianqi.2345.com/t/wea_history/js/" month "/58457_" month ".js"
for?month?in?months
]
2 批量下載數(shù)據(jù)
使用 requests 庫獲取 js 文件中的數(shù)據(jù),并存到 datas 變量中。import?requests
datas?=?[]
for?url?in?todo_urls:
r?=?requests.get(url,?headers?=?headers)
if?r.status_code!=200:
raise?Exception()
#?去除javascript前后的字符串,得到一個(gè)js格式的JSON
data?=?r.text.lstrip("var?weather_str=").rstrip(";")
datas.append(data)
3 解析數(shù)據(jù)
我們從 js 文件獲取的數(shù)據(jù) json 格式存儲(chǔ)的,需要使用 demjson 對(duì)數(shù)據(jù)進(jìn)行解析。#?解析所有月份的數(shù)據(jù)
all_datas?=?[]
for?data?in?datas:
tqInfos?=?demjson.decode(data)["tqInfo"]
all_datas.extend([x?for?x?in?tqInfos?if?len(x)>0])
4 將結(jié)果導(dǎo)入 csv 文件import?csv
with?open('./hangzhou_tianqi_2019.csv',?'w',?newline='',?encoding='utf-8')?as?csv_file:
writer?=?csv.writer(csv_file)
columns?=?list(all_datas[0].keys())
writer.writerow(columns)
for?data?in?all_datas:
writer.writerow([data[column]?for?column?in?columns])
5 結(jié)果展示
沒想到我們也可以用python爬蟲來看天氣預(yù)報(bào)吧,這可比很早之前我們守在電視機(jī)前等待要方便多了,而且操作有趣。更多Python學(xué)習(xí)推薦:JQ教程網(wǎng)Python大全。
總結(jié)
以上是生活随笔為你收集整理的python爬虫天气预报难不难_python爬虫可以用来看天气预报吗?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: crontab shell 每5秒执行_
- 下一篇: mysql 优化配置 大批量数据插入_p