API爬取天氣預報數據


API爬取天氣預報數據

"""

和風天氣API:https://id.heweather.com/

該網站為個人開發者提供免費的天氣預報數據,自行訪問官網注冊,在控制台看到個人的key。

然后看API文檔,基本可以開發了,有訪問次數限制。

"""

爬取數據代碼

import requests
import time
import pymongo

"""
和風天氣API提供了3000多個城市的天氣預報,我們先獲取這些城市的cid,
再循環獲取3000個城市的天氣預報,
存入mongodb

"""
#建立mongodb的連接
client=pymongo.MongoClient(host="localhost",port=27017)

#建立數據庫weather
book_weather=client['weather']

#在weather數據庫中建立集合:sheet_collection_1
sheet_weather=book_weather['sheet_collection_1']
  • 1:獲取網站給我們提供的天氣預報csv文件。


#獲取city的cid	地區/城市ID	CN101080402
#:獲取城市列表的url
url="https://a.hecdn.net/download/dev/china-city-list.csv"

#請求ulr
strhtml=requests.get(url)
strhtml.encoding='utf-8'

#返回字符串內容,csv格式
data=strhtml.text
# print(data)

#轉為列表
data1=data.split('\r')

#去除前兩行標題頭
for i in range(2):
    data1.remove(data1[0])

for item in data1:
    # print(item[0:12])
  • 2:調用接口獲取數據
    weather_url='https://free-api.heweather.net/s6/weather/now?location='+item[0:12].strip()+'&key=13e99fe03be0440cb9ff12e2edfe1ab6'
    # print(weather_url)
    weather_html=requests.get(weather_url)
    weather_html.encoding="utf-8"
    time.sleep(2)
    # print(weather_html.text)
    dic=weather_html.json()
  • 3:通過在線json解析工具,找到我們需要的數據,再插入到mongodb中
    city=dic["HeWeather6"][0]["basic"]["location"]
    twt=dic["HeWeather6"][0]["now"]["tmp"]
    ws=dic["HeWeather6"][0]["now"]["cond_txt"]
    w_date=dic["HeWeather6"][0]["update"]["loc"]
    

    #插入數據到mongodb中
    sheet_weather.insert_one({"城市":city,"氣溫":twt,"天氣情況":ws,"天氣日期":w_date})

    print("城市代碼:{0}".format(item[0:12].strip()))
  • 4調試能獲取到想要的數據之后,

    傳到linux系統中運行

ubuntu@ubuntu:~$ rz -y
rz waiting to receive.
Starting zmodem transfer.  Press Ctrl+C to cancel.
Transferring pymongo-3.10.1-cp37-cp37m-manylinux2014_x86_64.whl...
  100%     451 KB     451 KB/sec    00:00:01       0 Errors  

#安裝pymongo
ubuntu@ubuntu:~$ pip3 install pymongo-3.10.1-cp37-cp37m-manylinux2014_x86_64.whl 
Defaulting to user installation because normal site-packages is not writeable
Processing ./pymongo-3.10.1-cp37-cp37m-manylinux2014_x86_64.whl
Installing collected packages: pymongo
Successfully installed pymongo-3.10.1

#運行
ubuntu@ubuntu:~$ nohup python get_city.py &
[1] 12938
ubuntu@ubuntu:~$ nohup: ignoring input and appending output to 'nohup.out'

#查看,輸出
ubuntu@ubuntu:~$ tail -f nohup.out 
城市代碼:CN101010100
城市代碼:CN101010200
城市代碼:CN101010300
城市代碼:CN101010400
城市代碼:CN101010500
城市代碼:CN101010600


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM