You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Scrapy爬虫提取亚马逊书籍描述遇问题,求解决方案

解决亚马逊书籍描述提取的Scrapy方案

问题分析

你之前的代码存在两个核心问题:

  • 依赖的a-expander-content-expanded类是页面交互(点击"展开"按钮)后才生成的动态类,静态HTML中不存在这个类,导致选择器无法匹配目标元素
  • 用正则替换HTML标签的方式不够可靠,且仅提取span标签内的内容,会遗漏其他标签(如p)中的描述文本

可行解决思路

1. 静态抓取(优先尝试)

亚马逊部分书籍的描述会在初始HTML中存在,只是被折叠,可通过更稳定的选择器直接提取文本:

# 定位到产品描述的容器,提取所有文本节点
description_fragments = response.css('#productDescription .a-expander-content ::text').getall()
# 清理空白内容并拼接成完整描述
clean_description = ' '.join([fragment.strip() for fragment in description_fragments if fragment.strip()])

这里用#productDescription作为父容器定位,比直接依赖多个动态类更稳定,::text会提取目标元素下所有层级的文本内容,无需手动处理HTML标签。

2. 动态渲染抓取(静态抓取失效时)

如果静态HTML中完全没有描述内容,说明是JavaScript动态加载的,需要集成Playwright渲染页面:

  • 先安装依赖:pip install scrapy-playwright
  • 在Scrapy项目的settings.py中添加配置:
DOWNLOAD_HANDLERS = {
    "http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
    "https": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
}

PLAYWRIGHT_LAUNCH_OPTIONS = {
    "headless": True,  # 无头模式运行,如需可视化可设为False
}
  • 编写爬虫代码:
import scrapy

class AmazonBookSpider(scrapy.Spider):
    name = "amazon_book"
    start_urls = ["https://www.amazon.com/Local-Woman-Missing-Mary-Kubica/dp/1665068671"]

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, meta={"playwright": True})

    def parse(self, response):
        # 同样的文本提取逻辑
        description_fragments = response.css('#productDescription .a-expander-content ::text').getall()
        clean_description = ' '.join([fragment.strip() for fragment in description_fragments if fragment.strip()])
        yield {"book_description": clean_description}

3. 验证选择器有效性

可以在Scrapy shell中测试选择器:

scrapy shell https://www.amazon.com/Local-Woman-Missing-Mary-Kubica/dp/1665068671
# 测试选择器是否能匹配到元素
response.css('#productDescription .a-expander-content')

如果返回空列表,说明需要用动态渲染方案。

内容的提问来源于stack exchange,提问作者Raouf Yahiaoui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:45:50