爬虫python学习代码记录2-用API爬取天气预报数据

 Python3 爬虫、数据清洗与可视化实战

用API爬取天气预报数据,并将数据存入MongoDB中

import pandas as pd
import requests
import time
import pymongo #加载pymongo库
# 建立连接
client = pymongo.MongoClient('localhost',27017)
# 在MongoDB中新建名为weather的数据库
book_weather = client['weather']
# 在weather数据库中新建名为temp的表
sheet_weather = book_weather['sheet_weather_3']
data = pd.read_csv(r"C:\Users\烟雨潇潇\Desktop\芝士\CSDN\LocationList-master\China-City-List-latest.csv")
for i in range(1,len(data)): #len(data)
    location = data.iloc[i,0]
    basic_city = data.iloc[i,2]
    url = 'https://devapi.qweather.com/v7/weather/now?location='+location+'&key=32fe363ba31d428098fea10fd65f211f'
    strhtml = requests.get(url)
    strhtml.encoding = 'utf8'
    time.sleep(1)
    dic = strhtml.json()
    print(i)
    # code=402,表示超过访问次数或余额不足以支持继续访问服务
    if dic["code"] == "402":
        break
    # 向表中写入一条数据
    sheet_weather.insert_one(dic)
    # 在表中储存城市名称字段
    sheet_weather.update_one({'_id':dic['_id']},{'$set':{'city':basic_city}})

可以在Mongo DB Browser里查到

MongoDB数据库查询

1. 查询北京的天气预报数据

2. 查询实时气温低于5摄氏度的城市名称

import pymongo #加载pymongo库
# 建立连接
client = pymongo.MongoClient('localhost',27017)
# 在MongoDB中新建名为weather的数据库
book_weather = client['weather']
# 在weather数据库中新建名为temp的表
sheet_weather = book_weather['sheet_weather_3']
# 查找键city值为北京的数据
for item in sheet_weather.find({'city':'北京'}):
    print(item)
# 查询实时气温低于5摄氏度的城市名称
for item in sheet_weather.find():
    if item['code'] == "402":
        break
    tmp = item['now']['temp']
    # 使用update_one方法,将表中实时气温数据修改为数值型数据
    sheet_weather.update_one({'_id':item['_id']},{'$set':{'now.temp':int(tmp)}})
for item in sheet_weather.find({'now.temp':{'$lt':5}}):  # lt小于
    print(item['city'])

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值