标签:url 城市 dic 爬取 API ubuntu weather 天气预报 pymongo
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
标签:url,城市,dic,爬取,API,ubuntu,weather,天气预报,pymongo 来源: https://www.cnblogs.com/zhoujun007/p/12543091.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。