用API获取天气预报,和风天气实战
import requests
import time
import csv
# 和风天气网站https://dev.heweather.com/docs/api/weather
# 加载pymongo库,可以在cmd中用pip安装,也可以在settings中的project interpreter安装库
import pymongo
# 连接数据库
client=pymongo.MongoClient('localhost',27017)
# 在MongoDB中新建weather数据库
book_weather=client['weather']
# 在weather数据库中新建sheet_weather_3表
sheet_weather=book_weather['sheet_weather_3']
# 获取城市的位置ID,读取csv文件的第一列,每一行的第一个
with open('D:\数据可视化\大数据分析学习\China-City-List-latest.csv','r',encoding='utf-8') as f:
reader=csv.reader(f)
c=[row[0]for row in reader]
print(c)
# 移除前两个没用的数据
c.remove(c[0])
c.remove(c[0])
for item in c:
# 接口的url
url='https://devapi.heweather.net/v7/weather/3d?location='+item+'&key=d5bac6113f134116a4f7f49f52714a37'
# print(url)
strhtml=requests.get(url)
# 转换编码格式
strhtml.encoding='utf-8'
# 防止频繁访问服务器
time.sleep(1)
print(strhtml.text)
dic=strhtml.json()
# 插入表中
sheet_weather.insert_one(dic)
获取每个城市的location_ID,获得该城市的3天天气预报,但是没办法区分每个城市
加一个没办法查询天气数据的代码吧
import pymongo
client=pymongo.MongoClient('localhost',27017)
book_weather=client['weather']
sheet_weather=book_weather['sheet_weather']
for item in sheet_weather.find({'updateTime':'2020-09-17T13:35+08:00'}):
print(item)