Python爬虫与MongoDB的完美结合

🔸 Windows和Linux下MongoDB环境搭建

Windows下安装MongoDB
  1. 访问MongoDB官网,下载适用于Windows的MongoDB安装包。
  2. 双击安装包,选择"Complete"安装类型。
  3. 设置安装路径和数据存储路径,完成安装。

完成安装后,启动MongoDB服务:

bash 复制代码
"C:\Program Files\MongoDB\Server\4.4\bin\mongod.exe" --dbpath "C:\data\db"
Linux下安装MongoDB

在Linux系统下,通过包管理器安装MongoDB:

bash 复制代码
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
sudo apt-get update
sudo apt-get install -y mongodb-org

启动MongoDB服务:

bash 复制代码
sudo systemctl start mongod
sudo systemctl enable mongod

🔸 MongoDB写入规范

在Python中使用pymongo库写入数据到MongoDB:

python 复制代码
import pymongo

# 连接到MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["articles"]

# 插入单条数据
article = {
    "title": "文章标题",
    "author": "作者名",
    "content": "文章内容",
    "url": "http://example.com/article",
    "created_at": datetime.datetime.now()
}
collection.insert_one(article)

# 插入多条数据
articles = [
    {
        "title": "文章标题1",
        "author": "作者名1",
        "content": "文章内容1",
        "url": "http://example.com/article1",
        "created_at": datetime.datetime.now()
    },
    {
        "title": "文章标题2",
        "author": "作者名2",
        "content": "文章内容2",
        "url": "http://example.com/article2",
        "created_at": datetime.datetime.now()
    }
]
collection.insert_many(articles)

🔹 在这个示例中,我们使用insert_one方法插入单条数据,使用insert_many方法插入多条数据。


🔸 MongoDB对接爬虫实战

将以上知识结合起来,构建一个简单的爬虫,并将爬取到的数据存储到MongoDB中:

python 复制代码
import requests
from bs4 import BeautifulSoup
import pymongo
import datetime

# 爬取网页数据
url = 'http://example.com/articles'
response = requests.get(url)
html_content = response.content
soup = BeautifulSoup(html_content, 'html.parser')

# 连接到MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["articles"]

# 解析并插入数据
articles = soup.find_all('div', class_='article')
for article in articles:
    title = article.find('h1').text
    author = article.find('span', class_='author').text
    content = article.find('p', class_='content').text
    url = article.find('a')['href']
    
    article_data = {
        "title": title,
        "author": author,
        "content": content,
        "url": url,
        "created_at": datetime.datetime.now()
    }
    
    collection.insert_one(article_data)

🔹 在这个示例中,我们爬取网页中的文章数据,并将其插入到MongoDB的articles集合中,实现了爬虫和数据库的完美对接。


🔸 MongoDB优化

为了提升MongoDB的性能,可以考虑以下优化措施:

  1. 索引优化 :为常用的查询字段添加索引,例如文章集合中的titleurl字段。

    python 复制代码
    collection.create_index([("title", pymongo.TEXT)])
    collection.create_index([("url", pymongo.ASCENDING)], unique=True)
  2. 批量插入:一次性插入多条记录,减少写入操作次数。

    python 复制代码
    articles = [
        {
            "title": "标题1",
            "author": "作者1",
            "content": "内容1",
            "url": "http://example.com/1",
            "created_at": datetime.datetime.now()
        },
        {
            "title": "标题2",
            "author": "作者2",
            "content": "内容2",
            "url": "http://example.com/2",
            "created_at": datetime.datetime.now()
        }
    ]
    collection.insert_many(articles)
  3. 查询优化:使用适当的查询语句,避免全集合扫描。

    python 复制代码
    articles = collection.find({"title": {"$regex": "^Python"}}).limit(10)
    for article in articles:
        print(article)

🔹 通过这些优化措施,可以显著提升MongoDB的性能和查询效率。


🔸 总结

🔹 通过本次学习,我们掌握了在Windows和Linux系统下安装MongoDB,设计适合爬虫存储数据的写入规范,并通过实际爬虫示例展示了如何将爬取到的数据存储到MongoDB中。此外,还进行了MongoDB性能优化,提高了数据存储和查询的效率。

相关推荐
isyangli_blog几秒前
(1-4)Java Object类、Final、注解、设计模式、抽象类、接口、内部类
java·开发语言
三块钱07948 分钟前
【原创】基于视觉大模型gemma-3-4b实现短视频自动识别内容并生成解说文案
开发语言·python·音视频
易只轻松熊9 分钟前
C++(20): 文件输入输出库 —— <fstream>
开发语言·c++·算法
芯眼12 分钟前
ALIENTEK精英STM32F103开发板 实验0测试程序详解
开发语言·c++·stm32·单片机·嵌入式硬件·社交电子
神码小Z14 分钟前
Ubuntu快速安装Python3.11及多版本管理
python
JOYUAGV28 分钟前
Word压缩解决方案
python·word
TiDB 社区干货传送门43 分钟前
从开发者角度看数据库架构进化史:JDBC - 中间件 - TiDB
数据库·oracle·中间件·tidb·数据库架构
mahuifa1 小时前
(9)python开发经验
python·开发经验
虾球xz1 小时前
游戏引擎学习第280天:精简化的流式实体sim
数据库·c++·学习·游戏引擎
青出于兰1 小时前
C语言| 指针变量的定义
c语言·开发语言