热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

本内容衔接:爬虫学习二一:下载并安装MongoDB下载链接:http:dl.mongodb.orgdlwin32x86_64照着这篇博

本内容衔接 : 爬虫学习二




一: 下载并安装 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 pymongoclient = 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' #国内城市IDdata = 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后加上城市IDurl = '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 表示符号<&#61;
$gt 表示符号 >
$gte 表示符号>&#61;

找出今日最高温度大于20度的城市

import pymongoclient &#61; pymongo.MongoClient(&#39;localhost&#39;,27017) #创建连接book_weather &#61; client[&#39;weather&#39;]sheet_weather &#61; book_weather[&#39;sheet_weather&#39;]# for item in sheet_weather.find():
# tmp &#61; item["HeWeather6"][0]["daily_forecast"][0][&#39;tmp_max&#39;]#将最高温度设置为int类型,第一个参数表示要更新的条件#第二个参数表四要更新的信息
# sheet_weather.update_one({&#39;_id&#39;:item[&#39;_id&#39;]},{&#39;$set&#39;:{&#39;HeWeather6.0.daily_forecast.0.tmp_max&#39;:int(tmp)}})for item in sheet_weather.find({&#39;HeWeather6.0.daily_forecast.0.tmp_max&#39;:{&#39;$gt&#39;:20}}):print(item[&#39;HeWeather6&#39;][0][&#39;basic&#39;][&#39;location&#39;])

运行结果&#xff1a;
在这里插入图片描述



找出今日为西北风的城市&#xff1a;

import pymongocilent &#61; pymongo.MongoClient(&#39;localhost&#39;,27017)book_weather &#61; cilent[&#39;weather&#39;]sheet_weather &#61; book_weather[&#39;sheet_weather&#39;]for item in sheet_weather.find({&#39;HeWeather6.0.daily_forecast.0.wind_dir&#39;:&#39;西北风&#39;}):print(item[&#39;HeWeather6&#39;][0][&#39;basic&#39;][&#39;location&#39;])

运行结果&#xff1a;
在这里插入图片描述


推荐阅读
author-avatar
mobiledu2502927333
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有