【爬虫学习三】 Python将爬取的数据存储到MongoDB中
本内容衔接 :
一: 下载并安装 MongoDB
下载链接:http://dl.mongodb.org/dl/win32/x86_64
照着这篇博客配置完就行:
二:在pycharm中安装Mongo Plugin
File → settings → plugins 输入mongo 安装 Mongo Plugin
安装成功后重启pycharm生效
三: 将数据存入MongoDB中
import requests
import time
import pymongo
client = pymongo.MongoClient(localhost,27017) #创建连接
book_weather = client[weather] #创建名为 "weather" 的数据库
sheet_weather = book_weather[sheet_weather] #在"weather"数据库中建表"sheet_weather"
url = http://cdn.heweather.com/china-city-list.txt #国内城市ID
data = requests.get(url) #获取网页数据
data.encoding = utf8 #数据的编码方式为utf8,否则会乱码
data1 = data.text.split("
") #通过split将文本转换为列表
for i in range(6): #删除前6行不需要的数据
data1.remove(data1[0])
for item in data1:
#接口链接中的key后面的xxx改为自己刚刚注册的key,location后加上城市ID
url = https://free-api.heweather.net/s6/weather/forecast?key=xxx&location= + item[2:13]
data2 = requests.get(url)
data2.encoding = utf8
#time.sleep(1) #避免访问服务器过于频繁,每次访问等待1s(这里可以不加)
dic = data2.json()
sheet_weather.insert_one(dic) #向表中插入数据
运行结果: (1)成功创建数据库
(2) 双击表后看到内容(可以查看JSON的数据结构):
四: MongoDB数据库查询
$lt 表示符号 < $lte 表示符号<= $gt 表示符号 > $gte 表示符号>=
找出今日最高温度大于20度的城市
import pymongo
client = pymongo.MongoClient(localhost,27017) #创建连接
book_weather = client[weather]
sheet_weather = book_weather[sheet_weather]
# for item in sheet_weather.find():
# tmp = item["HeWeather6"][0]["daily_forecast"][0][tmp_max]
#将最高温度设置为int类型,第一个参数表示要更新的条件
#第二个参数表四要更新的信息
# sheet_weather.update_one({_id:item[_id]},{$set:{HeWeather6.0.daily_forecast.0.tmp_max:int(tmp)}})
for item in sheet_weather.find({
HeWeather6.0.daily_forecast.0.tmp_max:{
$gt:20}}):
print(item[HeWeather6][0][basic][location])
运行结果:
找出今日为西北风的城市:
import pymongo
cilent = pymongo.MongoClient(localhost,27017)
book_weather = cilent[weather]
sheet_weather = book_weather[sheet_weather]
for item in sheet_weather.find({
HeWeather6.0.daily_forecast.0.wind_dir:西北风}):
print(item[HeWeather6][0][basic][location])
运行结果:
