php解析和风天气api,API爬取天气预报数据

API爬取天气预报数据

"""

该网站为个人开发者提供免费的天气预报数据,自行访问官网注册,在控制台看到个人的key。

然后看API文档,基本可以开发了,有访问次数限制。

"""

10fca0980074790602ab4df586157408.png

爬取数据代码

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文件。

77a91da026a2aed852707e4ec56f6542.png

fd0ea950f3de8e0e315d486e996a8443.png

#获取city的cid地区/城市IDCN101080402

#:获取城市列表的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值