python爬取天气数据并导入mongodb中进行增删查改
时间: 2023-08-24 19:06:33 浏览: 64
你可以使用 Python 中的 requests、BeautifulSoup 和 pymongo 库来爬取天气数据并导入到 MongoDB 数据库中进行增删查改操作。
下面是一个简单的示例代码,可以爬取某个城市的天气数据并将其存储到 MongoDB 中:
```python
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 设置要爬取的城市名称和链接
city_name = '上海'
url = f'http://www.weather.com.cn/weather/{101020100}.shtml'
# 发送请求并获取响应
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
# 获取天气数据
weather_data = {
'city': city_name,
'date': soup.find('input', id='fc_24h_internal_update_time').get('value'),
'temperature': soup.find('p', class_='tem').span.text,
'weather': soup.find('p', class_='wea').text,
'wind': soup.find('p', class_='win').span.text
}
# 连接 MongoDB 数据库
client = MongoClient('mongodb://localhost:27017/')
db = client['weather']
col = db['weather_data']
# 插入数据
col.insert_one(weather_data)
# 查询数据
result = col.find_one({'city': city_name})
print(result)
# 更新数据
col.update_one({'city': city_name}, {'$set': {'temperature': '20℃'}})
# 删除数据
col.delete_one({'city': city_name})
```
需要注意的是,如果要在 MongoDB 中进行增删查改操作,需要先连接到 MongoDB 数据库,并获取到要操作的集合(collection)。在本示例中,我们连接到名为 "weather" 的数据库,并获取到名为 "weather_data" 的集合。同时,需要根据具体需求来编写插入、查询、更新和删除数据的代码。