【爬虫学习三】 Python将爬取的数据存储到MongoDB中

本内容衔接 : 爬虫学习二


一: 下载并安装 MongoDB

下载链接:http://dl.mongodb.org/dl/win32/x86_64

照着这篇博客配置完就行:配置MongoDB


二:在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("\n") #通过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'])

运行结果:
在这里插入图片描述

  • 11
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值