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
posted @ 2020-03-21 22:48  Noob52037  阅读(1416)  评论(0编辑  收藏  举报