【100天精通python】Day44:python网络爬虫开发_爬虫基础(爬虫数据存储:基本文件存储,MySQL,NoSQL:MongDB,Redis 数据库存储+实战代码)

目录

1 数据存储

1.1 爬虫存储:基本文件存储

1.2 爬虫存储:使用MySQL 数据库

1.3 爬虫 NoSQL 数据库使用

1.3.1 MongoDB 简介

1.3.2 MongoDB 使用

1.3.1 爬虫存储:使用MongoDB 数据库

1.4 Redis 数据库的使用

1.4.1 主要特点

1.4.2 常见用途

1.4.3 使用 Redis 数据库

 1.4.4 爬虫存储:使用 Redis 数据库

2 实战 网络爬虫数据存储示例

3 实战 抓取一个网页上的书籍信息

1 数据存储

1.1 爬虫存储:基本文件存储

   在爬虫中,你可以使用不同的格式将抓取到的数据存储下来,如文本文件(txt)、JSON文件、CSV文件等。

文本文件存储示例:

with open('data.txt', 'w') as file:
    file.write('Hello, World!')

JSON 文件存储示例:

import json

data = {'name': 'John', 'age': 30}
with open('data.json', 'w') as file:
    json.dump(data, file)

CSV 文件存储示例:

import csv

data = [['name', 'age'], ['John', 30], ['Alice', 25]]
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

1.2 爬虫存储:使用MySQL 数据库

        MySQL 是一种关系型数据库管理系统,你可以使用 Python 的 mysql.connector 模块连接和操作 MySQL 数据库。

        爬虫中使用 MySQL 数据库的基本步骤包括连接到数据库、创建数据表、将抓取到的数据存储到数据库中。以下是一个简单的示例,演示如何在爬虫中使用 MySQL 数据库存储抓取到的书籍信息。

实例:将抓取的书籍信息存储到 MySQL 数据库中

首先,确保你已经安装了 mysql-connector-python 库,它是 Python 连接 MySQL 数据库的库。

pip install mysql-connector-python

然后,你需要在 MySQL 数据库中创建一个名为 books 的数据库,以及一个名为 book_info 的数据表,用于存储书籍信息。

CREATE DATABASE books;
USE books;

CREATE TABLE book_info (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255),
    author VARCHAR(255),
    price DECIMAL(10, 2)
);

接下来,你可以使用以下代码示例,将抓取到的书籍信息存储到 MySQL 数据库中: 

import requests
import mysql.connector
from bs4 import BeautifulSoup

# 抓取数据
url = 'https://www.example.com/books'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 连接到 MySQL 数据库
connection = mysql.connector.connect(
    host='localhost',
    user='username',
    password='password',
    database='books'
)
cursor = connection.cursor()

# 解析并存储数据到数据库
book_elements = soup.find_all('div', class_='book')
for book_element in book_elements:
    title = book_element.find('h2').text
    author = book_element.find('p', class_='author').text
    price = float(book_element.find('p', class_='price').text.replace('$', ''))
    
    # 插入数据
    insert_query = "INSERT INTO book_info (title, author, price) VALUES (%s, %s, %s)"
    values = (title, author, price)
    cursor.execute(insert_query, values)

connection.commit()

# 关闭连接
cursor.close()
connection.close()

print("Book data saved to MySQL database.")

这个实例演示了如何将抓取到的书籍信息存储到 MySQL 数据库中。在实际应用中,你需要根据实际情况修改数据库连接参数、网页解析方式以及数据表结构。同时,你还可以添加异常处理等机制以保证数据存储的稳定性。 

1.3 爬虫 NoSQL 数据库使用

        NoSQL(Not Only SQL)是一种非关系型数据库,不使用传统的表格和关系来存储数据。它适用于大规模、高性能、分布式环境下的数据存储。

1.3.1 MongoDB 简介

        MongoDB 是一个开源的 NoSQL 数据库,以文档形式存储数据。它具有灵活的模式设计、横向可扩展性和高性能的特点。

1.3.2 MongoDB 使用

from pymongo import MongoClient

# 创建数据库连接
client = MongoClient('mongodb://localhost:27017/')

# 创建或选择数据库和集合
db = client['mydb']
collection = db['mycollection']

# 插入文档
data = {'name': 'John', 'age': 30}
insert_result = collection.insert_one(data)
print(insert_result.inserted_id)

# 查询文档
query = {'name': 'John'}
result = collection.find_one(query)
print(result)

# 更新文档
update_query = {'name': 'John'}
new_values = {'$set': {'age': 31}}
collection.update_one(update_query, new_values)

# 删除文档
delete_query = {'name': 'John'}
collection.delete_one(delete_query)

# 关闭连接
client.close()

1.3.1 爬虫存储:使用MongoDB 数据库

        在爬虫中使用 MongoDB 数据库的步骤包括连接到数据库、创建集合(类似于表格)、将抓取到的数据存储到集合中。以下示例,演示如何在爬虫中使用 MongoDB 数据库存储抓取到的书籍信息。

实例:将抓取的书籍信息存储到 MongoDB 数据库中

首先,确保你已经安装了 pymongo 库,它是 Python 连接 MongoDB 数据库的库。

pip install pymongo

然后,你需要启动 MongoDB 数据库,并创建一个数据库(例如 books_db)以及一个集合(例如 book_collection)。

接下来,你可以使用以下代码示例,将抓取到的书籍信息存储到 MongoDB 数据库中:

import requests
import pymongo
from bs4 import BeautifulSoup

# 抓取数据
url = 'https://www.example.com/books'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 连接到 MongoDB 数据库
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['books_db']
collection = db['book_collection']

# 解析并存储数据到集合
book_elements = soup.find_all('div', class_='book')
for book_element in book_elements:
    title = book_element.find('h2').text
    author = book_element.find('p', class_='author').text
    price = float(book_element.find('p', class_='price').text.replace('$', ''))
    
    # 插入数据
    book_data = {'title': title, 'author': author, 'price': price}
    collection.insert_one(book_data)

print("Book data saved to MongoDB database.")

         这个实例演示了如何将抓取到的书籍信息存储到 MongoDB 数据库中。在实际应用中,你需要根据实际情况修改数据库连接参数、网页解析方式以及集合名称。同时,你还可以添加异常处理等机制以保证数据存储的稳定性。

1.4 Redis 数据库的使用

    Redis 数据库它通常用于缓存、数据存储、消息队列等场景。下面详细解释 Redis 的用途,并提供一个基本的示例,演示如何在 Python 中使用 Redis。

1.4.1 主要特点

  1. 内存数据库: Redis 数据库将数据存储在内存中,因此访问速度非常快。
  2. 多种数据结构: Redis 支持多种数据结构,如字符串、哈希、列表、集合、有序集合等,使得它适用于不同的数据存储需求。
  3. 持久化: Redis 可以将内存中的数据持久化到磁盘,以便在重启后恢复数据。
  4. 分布式: Redis 支持分布式部署,可以设置主从复制、分片等机制。
  5. 高性能: Redis 使用高效的数据结构和存储引擎,具有出色的读写性能。
  6. 事务支持: Redis 支持事务,可以将多个操作打包成一个事务进行执行,确保原子性。
  7. 发布/订阅: Redis 提供发布/订阅机制,用于实现消息发布和订阅模式。
  8. 过期时间: 可以为键设置过期时间,过期后键将自动删除。
  9. Lua 脚本: Redis 支持执行 Lua 脚本,可以在服务器端执行复杂操作。

1.4.2 常见用途

  1. 缓存: Redis 适用于缓存常用的数据,加速数据访问。
  2. 会话管理: 在 Web 应用中,可以使用 Redis 存储用户会话信息。
  3. 实时统计: Redis 可以用于实时统计、计数器等功能。
  4. 消息队列: Redis 的发布/订阅机制可以实现轻量级的消息队列。
  5. 排行榜: Redis 的有序集合可以用于实现排行榜等功能。
  6. 分布式锁: 使用 Redis 可以实现分布式锁,控制并发访问。
  7. 缓解数据库负载: 将一部分查询结果存储在 Redis 中,减轻数据库的负载。

1.4.3 使用 Redis 数据库

Redis(Remote Dictionary Server)是一种开源的高性能键值存储系统,它被广泛用于各种应用场景,包括缓存、数据存储、消息队列、计数器、实时分析等。

 1 安装 redis 模块

pip install redis

    2 使用示例

import redis

# 创建连接
r = redis.Redis(host='localhost', port=6379, db=0)

# 存储数据
r.set('key', 'value')  # 存储字符串类型数据
r.hset('user:1', 'name', 'John')  # 存储哈希类型数据
r.hset('user:1', 'age', 30)  # 存储哈希类型数据

# 获取数据
value = r.get('key')
print("Value:", value.decode('utf-8'))

user_info = r.hgetall('user:1')
print("User Info:", user_info)

# 删除数据
r.delete('key')
r.hdel('user:1', 'age')

# 设置过期时间
r.setex('key', 3600, 'value')  # 设置键的过期时间(单位为秒)

# 发布和订阅
def subscriber():
    pubsub = r.pubsub()
    pubsub.subscribe(['channel'])  # 订阅名为 'channel' 的频道
    for message in pubsub.listen():
        print("Received:", message['data'])
        
def publisher():
    r.publish('channel', 'Hello, Subscribers!')  # 向频道发布消息

# 事务
def perform_transaction():
    with r.pipeline() as pipe:
        while True:
            try:
                pipe.watch('balance')  # 监视键 'balance'
                balance = int(pipe.get('balance'))
                if balance >= 10:
                    pipe.multi()  # 开始事务
                    pipe.decrby('balance', 10)  # 减少余额
                    pipe.incrby('expenses', 10)  # 增加支出
                    pipe.execute()  # 执行事务
                    break
                else:
                    print("Insufficient balance.")
                    break
            except redis.WatchError:
                continue

# 持久化
r.save()  # 手动触发持久化操作
r.bgsave()  # 后台进行持久化

# 关闭连接
r.close()

这些示例介绍了如何使用不同的存储方式(文本、JSON、CSV、数据库)来存储爬虫抓取到的数据,以及如何连接和操作 MySQL、MongoDB 和 Redis 数据库。具体用法会根据你的需求和环境略有不同,你可以根据这些示例进行更深入的学习和实践。

 1.4.4 爬虫存储:使用 Redis 数据库

实例:将抓取的网页链接存储到 Redis 数据库中

首先,确保你已经安装了 redis 库,它是 Python 连接 Redis 数据库的库。

然后,你需要启动 Redis 服务器。接下来,你可以使用以下代码示例,将抓取到的网页链接存储到 Redis 数据库中:

import requests
import redis
from bs4 import BeautifulSoup

# 抓取数据
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 连接到 Redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 解析并存储数据到 Redis 数据库
link_elements = soup.find_all('a')
for link_element in link_elements:
    link = link_element.get('href')
    if link and link.startswith('http'):
        r.sadd('links', link)

print("Links data saved to Redis database.")

在这个示例中,我们从目标网页中抓取所有链接,然后使用 Redis 的集合数据类型(sadd 方法)将这些链接存储到 Redis 数据库中。

这个实例只是一个简单的示范,你可以根据实际需求,将更多的功能添加到爬虫中,如数据清洗、去重、持久化等。同时,你需要根据实际情况配置 Redis 数据库的连接参数。

2 实战 网络爬虫数据存储示例

        以下是一个简单示例,演示如何在爬虫中将抓取到的数据存储到文本文件、JSON 文件和 MySQL 数据库中:

import requests
import json
import mysql.connector

# 抓取数据
response = requests.get('https://api.example.com/data')
data = response.json()

# 文本文件存储
with open('data.txt', 'w') as file:
    for item in data:
        file.write(f"{item['name']} - {item['value']}\n")

# JSON 文件存储
with open('data.json', 'w') as file:
    json.dump(data, file, indent=4)

# 数据库存储
connection = mysql.connector.connect(
    host='localhost',
    user='username',
    password='password',
    database='mydatabase'
)

cursor = connection.cursor()
for item in data:
    query = "INSERT INTO data_table (name, value) VALUES (%s, %s)"
    values = (item['name'], item['value'])
    cursor.execute(query, values)

connection.commit()
cursor.close()
connection.close()

3 实战 抓取一个网页上的书籍信息

一个简单的网络爬虫实例,涵盖了使用 urllib 库、Beautiful Soup 库、代理和数据存储的方面。在这个实例中,我们将抓取一个网页上的书籍信息,并将抓取到的数据存储到 JSON 文件中。

import urllib.request
from bs4 import BeautifulSoup
import json

# 定义目标网页的 URL
url = 'https://www.example.com/books'

# 定义代理(如果需要使用代理)
proxies = {'http': 'http://proxy.example.com:8080'}

# 发起请求,使用代理
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(req, proxies=proxies)

# 解析网页内容
soup = BeautifulSoup(response, 'html.parser')

# 创建一个空的书籍列表
books = []

# 获取书籍信息
book_elements = soup.find_all('div', class_='book')
for book_element in book_elements:
    title = book_element.find('h2').text
    author = book_element.find('p', class_='author').text
    price = book_element.find('p', class_='price').text
    books.append({'title': title, 'author': author, 'price': price})

# 存储到 JSON 文件
with open('books.json', 'w') as file:
    json.dump(books, file, indent=4)

print("Books data saved to 'books.json'")

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年8月28日
下一篇 2023年8月28日

相关推荐