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'])