如何保存提取的信息?
为了保存提取的信息,需要了解一些结果存储格式:
CSV – 是最常用的表格数据存储格式之一。它是一个文本文件,每一行代表一条记录,字段之间用逗号分隔。优点:被包括 Excel 在内的大多数数据处理软件支持,易于用文本编辑器阅读和修改。缺点:不适合存储复杂结构数据(例如嵌套数据),在处理逗号和特殊字符时需要转义。
JSON – 是一种用于数据交换的文本格式,非常适合表示结构化数据,在 Web 开发中广泛使用。优点:支持嵌套和层级结构;被大多数编程语言良好支持;人和机器都易于阅读。适用于通过 API 传输数据的场景。缺点:相比 CSV 文件体积更大;由于结构更复杂,解析速度可能更慢。
XLS – 用于 Excel 表格,存储单元格数据、格式和公式。常用于数据表格存储。在 Python 中处理 XLS 需要第三方库,例如 pandas。优点:数据展示清晰、适合可视化与报表。缺点:依赖额外库,会增加服务器负担和处理时间。
XML – 是一种用于存储和传输数据的标记语言,支持嵌套结构和属性。优点:结构化强,适合复杂数据;被多种标准和系统支持。缺点:文件较冗长,解析速度较慢。
数据库用于存储大量结构化数据。示例包括 MySQL、PostgreSQL、MongoDB、SQLite。优点:支持大规模数据与快速访问;易于组织与关联数据;支持事务与数据恢复。缺点:需要额外配置与维护。
对于我们的爬虫,我们选择 CSV 格式,因为提取的数据是表格型的(引用文本与作者、商品名称与链接),并且数据量较小,没有复杂嵌套结构。关于如何读写该格式的更多信息,可以查看 这里。在我们的引用代码中添加 CSV 导入,创建 writer 对象,并写入引用数据(引用内容及其作者):
with open('quotes.csv', 'w', newline='', encoding='utf-8') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(['引用', '作者'])
for quote in quotes[:3]:
text = quote.select_one('.text').get_text(strip=True)
author = quote.select_one('.author').get_text(strip=True)
csvwriter.writerow([text, author])
同时,我们还添加了控制台输出以及对可能错误的处理:
print("数据已成功写入 quotes.csv")
except requests.RequestException as e:
print(f'请求页面时发生错误: {e}')
except Exception as e:
print(f'发生错误: {e}')
完整代码如下:
import requests
from bs4 import BeautifulSoup
import csv
# 目标页面 URL
url = 'https://quotes.toscrape.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36'
}
try:
# 发送带有自定义 User-Agent 的 GET 请求
response = requests.get(url, headers=headers)
response.raise_for_status() # 检查 HTTP 错误
# 创建 BeautifulSoup 对象用于解析 HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 查找所有引用块
quotes = soup.select('.quote')
# 打开 CSV 文件进行写入
with open('quotes.csv', 'w', newline='', encoding='utf-8') as csvfile:
# 创建 writer 对象
csvwriter = csv.writer(csvfile)
# 写入表头
csvwriter.writerow(['引用', '作者'])
# 写入引用数据
for quote in quotes[:3]:
# 提取引用文本
text = quote.select_one('.text').get_text(strip=True)
# 提取作者名称
author = quote.select_one('.author').get_text(strip=True)
# 写入 CSV 文件
csvwriter.writerow([text, author])
print("数据已成功写入 quotes.csv")
except requests.RequestException as e:
print(f'请求页面时发生错误: {e}')
except Exception as e:
print(f'发生错误: {e}')
对第二个爬虫也执行同样的操作:
from playwright.sync_api import sync_playwright
import csv
# 目标页面 URL
url = 'https://parsemachine.com/sandbox/catalog/'
def scrape_with_playwright():
try:
with sync_playwright() as p:
# 启动 Chromium 浏览器
browser = p.chromium.launch(headless=False) # 如果需要无头模式,请改为 True
try:
# 打开新标签页
page = browser.new_page()
# 访问目标页面
page.goto(url)
# 查找所有商品卡片
product_cards = page.query_selector_all('.card.product-card')
# 打开 CSV 文件进行写入
with open('products.csv', 'w', newline='', encoding='utf-8') as csvfile:
# 创建 writer 对象
csvwriter = csv.writer(csvfile)
# 写入表头
csvwriter.writerow(['商品名称', '链接'])
# 从商品卡片中提取数据并写入 CSV
for card in product_cards:
# 提取商品名称
title_tag = card.query_selector('.card-title .title')
title = title_tag.inner_text() if title_tag else '无名称'
# 商品链接
product_link = title_tag.get_attribute('href') if title_tag else '无链接'
# 如果是相对链接,添加基础 URL
if product_link and not product_link.startswith('http'):
product_link = f'https://parsemachine.com{product_link}'
# 写入 CSV 文件
csvwriter.writerow([title, product_link])
# 输出商品信息
print(f'名称: {title}, 链接: {product_link}')
print("数据已成功写入 products.csv")
except Exception as e:
print(f'Playwright 运行时发生错误: {e}')
finally:
# 关闭浏览器
browser.close()
print("浏览器已关闭。")
except Exception as e:
print(f'启动 Playwright 时发生错误: {e}')
scrape_with_playwright()