Python 3爬虫开发常用库组合:Scrapy与BeautifulSoup实战技巧
详细讲解Python 3爬虫开发中Scrapy与BeautifulSoup的组合使用技巧,包括环境搭建、Spider编写、数据解析、Pipeline处理及常见问题排查,帮助开发者高效完成网页数据抓取任务。
Scrapy是Python生态中功能最完整的爬虫框架,提供请求调度、并发管理、中间件和数据管道等基础设施。BeautifulSoup则专注HTML/XML文档解析,接口直观、容错能力强。两者单独使用都很常见,但将BeautifulSoup嵌入Scrapy的Spider中做页面解析,可以同时获得Scrapy的工程能力和BeautifulSoup的灵活解析——这正是本文要展开的组合方式。下面从环境准备开始,逐步演示如何在一个Scrapy项目中用BeautifulSoup完成实际的数据抓取任务。
环境准备与安装
确保系统已安装Python 3.8或更高版本。打开终端,执行以下命令安装两个核心库:
pip install scrapy beautifulsoup4 lxml
这里同时安装了lxml,它是BeautifulSoup推荐的HTML解析器,速度比Python内置的html.parser快数倍,对不规范HTML的容错性也更好。安装完成后可以快速验证:
python -c "import scrapy; print(scrapy.__version__)"
python -c "import bs4; print(bs4.__version__)"
如果两条命令都正常输出版本号(例如2.11.0和4.12.3),说明安装成功。
创建Scrapy项目与Spider基本结构
用Scrapy的命令行工具创建项目骨架:
scrapy startproject book_scraper
cd book_scraper
scrapy genspider books example.com
执行后会生成如下目录结构:
book_scraper/
├── scrapy.cfg
└── book_scraper/
├── __init__.py
├── items.py
├── middlewares.py
├── pipelines.py
├── settings.py
└── spiders/
├── __init__.py
└── books.py
其中spiders/books.py是我们编写爬取逻辑的主要文件,items.py定义数据字段,pipelines.py处理数据存储,settings.py控制项目配置。
在Spider中集成BeautifulSoup解析页面
Scrapy默认使用自带的Selector(基于parsel/lxml和CSS选择器或XPath)做页面解析。要使用BeautifulSoup,只需在Spider的回调方法中将response.text传给BeautifulSoup即可,Scrapy的请求调度和下载流程完全不受影响。
先定义数据结构。编辑items.py:
import scrapy
class BookItem(scrapy.Item):
title = scrapy.Field()
price = scrapy.Field()
rating = scrapy.Field()
availability = scrapy.Field()
description = scrapy.Field()
然后编写Spider。以抓取一个图书列表页为例,编辑spiders/books.py:
import scrapy
from bs4 import BeautifulSoup
from book_scraper.items import BookItem
class BooksSpider(scrapy.Spider):
name = "books"
start_urls = ["https://books.toscrape.com/"]
def parse(self, response):
soup = BeautifulSoup(response.text, "lxml")
articles = soup.select("article.product_pod")
for article in articles:
detail_url = article.select_one("h3 a")["href"]
yield response.follow(detail_url, callback=self.parse_detail)
# 翻页
next_btn = soup.select_one("li.next a")
if next_btn:
yield response.follow(next_btn["href"], callback=self.parse)
def parse_detail(self, response):
soup = BeautifulSoup(response.text, "lxml")
item = BookItem()
item["title"] = soup.select_one("h1").get_text(strip=True)
price_tag = soup.select_one("p.price_color")
item["price"] = price_tag.get_text(strip=True) if price_tag else ""
star_tag = soup.select_one("p.star-rating")
if star_tag:
classes = star_tag.get("class", [])
rating_map = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
for cls in classes:
if cls in rating_map:
item["rating"] = rating_map[cls]
break
avail_tag = soup.select_one("p.instock.availability")
item["availability"] = avail_tag.get_text(strip=True) if avail_tag else ""
desc_tag = soup.select_one("#product_description ~ p")
item["description"] = desc_tag.get_text(strip=True) if desc_tag else ""
yield item
这段代码有几个要点值得注意:
BeautifulSoup(response.text, "lxml")每次只解析当前页面,不影响Scrapy的异步调度。response.follow()仍然使用Scrapy的方法来发起后续请求,保留了自动URL拼接和去重能力。soup.select()和soup.select_one()使用CSS选择器,写法与前端开发一致,在处理嵌套结构和兄弟选择器时比XPath更直观。get_text(strip=True)可以一步提取标签内的纯文本并去除首尾空白,省去手动清洗。
图1:Scrapy与BeautifulSoup在爬虫流程中的分工——Scrapy管理请求生命周期,BeautifulSoup专注页面解析
BeautifulSoup常用解析技巧
在Spider中使用BeautifulSoup时,以下几种解析模式最为实用。
1. CSS选择器精确定位
select()和select_one()支持标准CSS选择器语法,可以直接用浏览器开发者工具复制选择器路径后使用:
# 选择class为"product_pod"的article标签
articles = soup.select("article.product_pod")
# 选择id为"product_description"后面紧跟的p标签
desc = soup.select_one("#product_description ~ p")
# 选择data属性
items = soup.select('div[data-type="book"]')
# 嵌套选择:表格中第二列的所有链接
links = soup.select("table.result-list td:nth-child(2) a")
2. find系列方法处理复杂条件
当CSS选择器不够灵活时,find()和find_all()支持正则表达式和自定义函数:
import re
# 匹配所有以"product-"开头的class
items = soup.find_all("div", class_=re.compile(r"^product-"))
# 自定义过滤:找所有包含数字文本的span
def has_number(tag):
return tag.name == "span" and tag.string and re.search(r"\d+", tag.string)
price_spans = soup.find_all(has_number)
3. 处理嵌套与兄弟节点
BeautifulSoup提供导航属性来遍历文档树,这在处理不规则HTML时特别有用:
# 获取同级的下一个标签(跳过空白文本节点)
next_item = tag.find_next_sibling("div")
# 获取父级标签
parent = tag.find_parent("table")
# 提取标签的所有后代文本,用分隔符连接
full_text = tag.get_text(separator=" | ", strip=True)
4. 清洗与转换提取结果
提取到的文本经常需要进一步清洗。一个常见做法是在Item中配合简单函数处理:
def clean_price(raw):
"""去除货币符号,转为浮点数"""
digits = re.sub(r"[^\d.]", "", raw)
return float(digits) if digits else 0.0
item["price"] = clean_price(price_tag.get_text(strip=True))
图2:根据目标元素特征选择合适的BeautifulSoup解析方法
Pipeline数据处理与存储
Spider中yield item产出的数据会经过Pipeline层。在pipelines.py中编写处理逻辑,可以完成去重、清洗和持久化存储:
import json
class JsonWriterPipeline:
def open_spider(self, spider):
self.file = open("books.jsonl", "w", encoding="utf-8")
self.seen_titles = set()
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
title = item.get("title", "")
if title in self.seen_titles:
return item # 跳过重复
self.seen_titles.add(title)
line = json.dumps(dict(item), ensure_ascii=False)
self.file.write(line + "\n")
return item
在settings.py中启用Pipeline并配置合理的爬取速度:
# settings.py 关键配置
ITEM_PIPELINES = {
"book_scraper.pipelines.JsonWriterPipeline": 300,
}
# 遵守robots.txt
ROBOTSTXT_OBEY = True
# 控制请求频率,避免对目标站点造成压力
DOWNLOAD_DELAY = 1.5
CONCURRENT_REQUESTS = 4
# 设置合理的User-Agent
USER_AGENT = "BookScraper/1.0 (+https://example.com/bot)"
# 日志级别
LOG_LEVEL = "INFO"
运行爬虫:
scrapy crawl books
执行完成后,当前目录会生成books.jsonl文件,每行一条JSON记录。如果需要CSV格式,Scrapy也支持直接导出:
scrapy crawl books -O books.csv
Scrapy Selector与BeautifulSoup的选择时机
Scrapy自带的Selector在大多数场景下性能更好,因为它直接操作lxml的树结构而不需要额外构建BeautifulSoup的对象模型。那什么时候值得引入BeautifulSoup?以下是几个具体判断依据:
适合用BeautifulSoup的情况:
- 目标页面HTML严重不规范(未闭合标签、嵌套混乱),BeautifulSoup的容错解析器能更好地还原文档结构。
- 已有大量基于BeautifulSoup的解析代码需要迁移到Scrapy项目,避免重写。
- 需要频繁使用
get_text(separator=...)一类的便捷方法提取和清洗文本。 - 团队成员更熟悉BeautifulSoup的API,降低上手成本。
建议继续用Scrapy Selector的情况:
- 页面结构规整,XPath或CSS选择器就能快速定位。
- 需要处理大量页面,关注内存占用和解析速度。
- 需要用到Scrapy Selector特有的
.re()方法直接对选择结果做正则匹配。
两者并不互斥,可以在同一个Spider中混合使用。例如主体数据用Selector快速提取,遇到特殊的嵌套区块再局部用BeautifulSoup处理。
图3:两种解析方案的关键维度对比,帮助根据实际需求选择
实战中的常见问题与解决
编码问题
部分网站的页面编码与HTTP头声明不一致,导致中文乱码。Scrapy的response.text通常能自动处理,但如果出现问题,可以手动指定:
def parse(self, response):
# 强制使用gbk解码
html_text = response.body.decode("gbk", errors="replace")
soup = BeautifulSoup(html_text, "lxml")
动态加载内容
Scrapy默认不执行JavaScript,所以通过AJAX或前端框架动态加载的内容不会出现在response.text中。有两个实用的应对方式:
第一种是直接请求数据接口。打开浏览器开发者工具的Network面板,筛选XHR请求,找到实际返回数据的API地址。这类接口通常返回JSON,可以直接用json.loads(response.text)提取,不需要BeautifulSoup。
def parse_api(self, response):
data = json.loads(response.text)
for item in data.get("results", []):
yield {
"title": item["name"],
"price": item["price"],
}
第二种是在Scrapy中集成scrapy-splash或scrapy-playwright来渲染JavaScript。以scrapy-playwright为例:
# settings.py
DOWNLOAD_HANDLERS = {
"http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
"https": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
}
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
# spider中使用
yield scrapy.Request(
url,
meta={"playwright": True, "playwright_page_methods": [
{"method": "wait_for_selector", "selector": "div.loaded"},
]},
callback=self.parse_dynamic,
)
请求被拒绝或限流
如果爬虫频繁收到403或429状态码,除了降低请求频率,可以在settings.py中启用自动限速中间件:
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 2
AUTOTHROTTLE_MAX_DELAY = 30
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0
这个中间件会根据服务器响应时间自动调整请求间隔,比手动设置固定DOWNLOAD_DELAY更灵活。
完整项目的组织建议
当爬虫项目逐渐复杂时,合理的代码组织能避免后期维护困难。以下是经过实践验证的目录结构:
book_scraper/
├── scrapy.cfg
└── book_scraper/
├── items.py # 数据字段定义
├── pipelines.py # 清洗、去重、存储
├── settings.py # 全局配置
├── middlewares.py # 请求/响应中间件
├── utils/
│ ├── parsers.py # 通用解析函数
│ └── cleaners.py # 文本清洗工具
└── spiders/
├── books.py # 图书列表爬虫
└── reviews.py # 评论数据爬虫
把通用的BeautifulSoup解析逻辑抽到utils/parsers.py中,多个Spider可以复用:
# utils/parsers.py
from bs4 import BeautifulSoup
def extract_table(html_text, table_selector):
"""从HTML中提取指定表格的所有行数据"""
soup = BeautifulSoup(html_text, "lxml")
table = soup.select_one(table_selector)
if not table:
return []
rows = []
for tr in table.select("tr")[1:]: # 跳过表头
cells = [td.get_text(strip=True) for td in tr.select("td")]
if cells:
rows.append(cells)
return rows
图4:完整Scrapy项目的模块关系与数据流向总览
值得留意的细节
内存控制。BeautifulSoup会为每个页面创建完整的对象树,对于超大页面(几MB以上的HTML),内存占用会明显增加。如果只需要提取局部数据,可以先用字符串方法截取目标区域再传给BeautifulSoup:
# 只解析包含目标数据的表格部分
start = response.text.find('<table class="data">')
end = response.text.find('</table>', start) + len('</table>')
if start > -1:
soup = BeautifulSoup(response.text[start:end], "lxml")
错误处理。网络爬虫必然会遇到各种异常情况,在Spider中加入适当的保护:
def parse_detail(self, response):
if response.status != 200:
self.logger.warning(f"非200响应: {response.url} ({response.status})")
return
soup = BeautifulSoup(response.text, "lxml")
title_tag = soup.select_one("h1")
if not title_tag:
self.logger.warning(f"未找到标题: {response.url}")
return
item = BookItem()
item["title"] = title_tag.get_text(strip=True)
# ... 其余字段同样做空值检查
遵守抓取规范。在settings.py中保持ROBOTSTXT_OBEY = True,设置合理的DOWNLOAD_DELAY和CONCURRENT_REQUESTS,提供有意义的USER_AGENT标识。这些配置不仅是对目标网站的尊重,也能降低IP被封禁的风险。
Scrapy与BeautifulSoup的组合,本质上是用Scrapy的工程框架解决"怎么抓"的问题,用BeautifulSoup的灵活接口解决"怎么解析"的问题。掌握了上面的项目结构、集成方式和常见问题处理,就可以应对大部分网页数据抓取场景了。遇到更复杂的需求——比如分布式抓取或登录态维护——再在这个基础上扩展相应的中间件和配置即可。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









