作者:mobiledu2502927333 | 来源:互联网 | 2023-08-06 12:03
本内容衔接 : 爬虫学习二
一: 下载并安装 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'] sheet_weather = book_weather['sheet_weather'] url = 'http://cdn.heweather.com/china-city-list.txt' data = requests.get(url) data.encoding = 'utf8' data1 = data.text.split("\n") for i in range(6): data1.remove(data1[0])for item in data1:url = 'https://free-api.heweather.net/s6/weather/forecast?key=xxx&location=' + item[2:13]data2 = requests.get(url)data2.encoding = 'utf8'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({&#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;