亚马逊关联商品数据采集:从需求分析到生产部署的完整实践

简介: 本文详解亚马逊关联商品(Related Products)数据采集的三大工程挑战——模块碎片化、轮播截断、广告混入,并提供融合静态解析(lxml/BS4)与动态渲染(Playwright)的混合架构方案,含完整Python代码与生产级调度器,兼顾精度、性能与可维护性。

Amazon Price Comparison by Region How the Same ASIN Is Priced Across Six Marketplaces.png

一、核心痛点

亚马逊关联商品(Related Products)数据是跨境电商数据产品的高价值数据源。然而,与其他亚马逊数据字段相比,Related Products 采集有三个独特的工程挑战:

挑战一:模块碎片化。关联商品不是一个整体,是六个独立模块(FBT、Also Bought、Also Viewed、Similar Items、Sponsored、BSR Sidebar),容器 ID 各异,渲染方式不同,不能用一套代码统一处理。

挑战二:轮播截断。Also Bought 和 Also Viewed 模块以轮播展示,静态 HTML 只有首屏 4-6 个 ASIN,完整列表(15-20 个)需要动态翻页,且翻页机制因页面版本不同而有差异。

挑战三:广告混入。Sponsored Products 穿插在自然推荐里,HTML 标记不够显眼,容易与自然推荐混淆,影响数据质量。

本文提供从需求分析到生产部署的完整实践方案。


二、关键技术决策

2.1 静态 HTML 解析 vs. 动态渲染

模块 是否需要动态渲染 原因
FBT 否 服务端渲染,静态 HTML 完整
Also Bought 部分(首屏可静态) 轮播首屏服务端渲染,翻页需 JS
Also Viewed 部分(首屏可静态) 同上
Similar Items 视情况 部分版本需 JS
Sponsored 是 完全 JS 注入
BSR Sidebar 否 服务端渲染

架构决策:混合模式——先用 lxml/BeautifulSoup 处理静态可解析模块,对需要动态渲染的模块用 Playwright 补充,避免全量使用浏览器自动化带来的性能损耗。

2.2 代理选型

亚马逊对数据中心 IP 实施 ASN 级别的 TCP 丢弃,住宅代理是必须条件。推荐使用支持城市级别轮换的住宅代理服务,每个 session 的请求数控制在 5-10 次以内。


三、完整代码实现

3.1 核心提取器

from bs4 import BeautifulSoup
from dataclasses import dataclass, field
from typing import Optional
import re

@dataclass
class RelatedProduct:
    asin: str
    title: Optional[str] = None
    price: Optional[str] = None
    rating: Optional[float] = None
    review_count: Optional[int] = None
    image_url: Optional[str] = None
    is_sponsored: bool = False
    module: str = ""
    rank_in_module: int = 0


class AmazonRelatedExtractor:

    CONTAINERS = {
   
        "fbt":         ["sims-fbt", "frequently-bought-together_feature_div"],
        "also_bought": ["p_dp_sims_btf_1", "similarities_feature_div"],
        "also_viewed": ["p_dp_sims_btf_2", "session-sims-feature-div", "customers-also-viewed_feature_div"],
        "similar":     ["similarities_feature_div", "compare-similar-feature-div"],
        "bsr":         ["zg-right-col"]
    }

    def __init__(self, html: str):
        self.soup = BeautifulSoup(html, "lxml")

    def _find_container(self, module: str):
        for cid in self.CONTAINERS.get(module, []):
            c = self.soup.find(id=cid)
            if c:
                return c
        return None

    def _extract_asin(self, el) -> Optional[str]:
        a = el.get("data-asin", "").strip()
        if a and len(a) == 10:
            return a
        for link in el.find_all("a", href=True)[:2]:
            m = re.search(r"/dp/([A-Z0-9]{10})", link["href"])
            if m:
                return m.group(1)
        return None

    def _parse_card(self, card, module: str, rank: int) -> Optional[RelatedProduct]:
        asin = self._extract_asin(card)
        if not asin:
            return None
        p = RelatedProduct(asin=asin, module=module, rank_in_module=rank)

        # 标题
        for sel in [".a-size-base-plus", ".a-size-medium", ".a-truncate-cut"]:
            el = card.select_one(sel)
            if el:
                p.title = el.get_text(strip=True)[:200]
                break

        # 价格
        pw = card.select_one(".a-price-whole")
        pf = card.select_one(".a-price-fraction")
        if pw:
            p.price = f"${pw.get_text(strip=True).replace(',','')}.{pf.get_text(strip=True) if pf else '00'}"
        else:
            off = card.select_one(".a-price .a-offscreen")
            if off:
                p.price = off.get_text(strip=True)

        # 评分
        rel = card.select_one("[aria-label*='out of 5 stars']")
        if rel:
            m = re.search(r"([\d.]+)\s+out of 5", rel.get("aria-label",""))
            if m:
                try: p.rating = float(m.group(1))
                except: pass

        # 评论数
        rev = card.select_one("[aria-label$='ratings']") or card.select_one("[aria-label$='reviews']")
        if rev:
            m = re.search(r"([\d,]+)", rev.get("aria-label",""))
            if m:
                try: p.review_count = int(m.group(1).replace(",",""))
                except: pass

        # 图片
        img = card.select_one("img")
        if img:
            p.image_url = img.get("src") or img.get("data-src")

        # Sponsored
        p.is_sponsored = self._is_sponsored(card)
        return p

    def _is_sponsored(self, card) -> bool:
        if card.select_one(".s-sponsored-label-info-icon, .puis-sponsored-label-info-icon"):
            return True
        if "sponsored" in card.get("data-component-type","").lower():
            return True
        if "sponsored" in card.get_text()[:200].lower():
            return True
        return any("amazon-adsystem" in a.get("href","") for a in card.select("a[href]"))

    def extract_module(self, module: str) -> list[RelatedProduct]:
        container = self._find_container(module)
        if not container:
            return []
        results, seen = [], set()
        for rank, card in enumerate(container.select("[data-asin], .a-carousel-card"), 1):
            p = self._parse_card(card, module, rank)
            if p and p.asin not in seen:
                seen.add(p.asin)
                results.append(p)
        return results

    def extract_all(self) -> dict:
        modules = {
   }
        for module in ["fbt", "also_bought", "also_viewed", "similar", "bsr"]:
            modules[module] = self.extract_module(module)

        all_p = [p for lst in modules.values() for p in lst]
        modules["summary"] = {
   
            "total_unique_asins": len({
   p.asin for p in all_p}),
            "total_sponsored": sum(1 for p in all_p if p.is_sponsored),
            **{
   f"{k}_count": len(v) for k, v in modules.items() if isinstance(v, list)}
        }
        return modules

3.2 批量采集调度器

import time, random, json, logging
from pathlib import Path

logger = logging.getLogger(__name__)


def batch_scrape_related(
    asins: list[str],
    html_fetcher,         # 传入获取 HTML 的函数(可对接 Playwright 或 API)
    output_file: str = "related_products.jsonl",
    delay_range: tuple = (10, 25),
    resume: bool = True
) -> dict:
    """
    批量采集关联商品数据,支持断点续采

    Args:
        asins: 目标 ASIN 列表
        html_fetcher: function(asin: str) -> str,返回 HTML 字符串
        output_file: 输出文件路径(JSONL 格式,断点续采)
        delay_range: 请求间隔随机范围(秒)
        resume: 是否跳过已采集的 ASIN
    """
    output = Path(output_file)
    completed = set()

    # 加载已完成的 ASIN(断点续采)
    if resume and output.exists():
        with open(output, "r") as f:
            for line in f:
                try:
                    d = json.loads(line)
                    if d.get("source_asin"):
                        completed.add(d["source_asin"])
                except json.JSONDecodeError:
                    pass
        logger.info(f"断点续采:已完成 {len(completed)} 个 ASIN,跳过")

    remaining = [a for a in asins if a not in completed]
    logger.info(f"待处理:{len(remaining)} 个 ASIN")

    success, errors = 0, []

    for i, asin in enumerate(remaining, 1):
        logger.info(f"[{i}/{len(remaining)}] {asin}")
        try:
            html = html_fetcher(asin)
            if not html:
                raise ValueError("获取到空 HTML")

            extractor = AmazonRelatedExtractor(html)
            data = extractor.extract_all()
            data["source_asin"] = asin
            data["scraped_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

            with open(output, "a", encoding="utf-8") as f:
                f.write(json.dumps(data, ensure_ascii=False, default=vars) + "\n")

            logger.info(f"  FBT={len(data['fbt'])} | Also Bought={len(data['also_bought'])} | "
                       f"Also Viewed={len(data['also_viewed'])}")
            success += 1

        except Exception as e:
            logger.error(f"  失败: {e}")
            errors.append({
   "asin": asin, "error": str(e)})

        if i < len(remaining):
            delay = random.uniform(*delay_range)
            time.sleep(delay)

    logger.info(f"\n=== 完成 === 成功:{success} 失败:{len(errors)}")
    return {
   "success": success, "errors": errors}

四、Build vs. Buy 决策框架

指标 自建方案 Pangolinfo API
初始开发 2-4 周 1 天
月度维护 20-40 小时 0 小时
住宅代理成本 $50-200/月 内置
Cloudflare 更新应对 需工程介入 服务端透明更新
关联模块完整性 视维护质量 六大模块全覆盖
适合规模 < 500 ASIN/天 无限制

决策建议:

  • 日均 < 200 ASIN,有工程资源:自建,技术积累价值大
  • 日均 200-1000 ASIN:混合方案(自建 FBT/BSR 静态模块,API 处理动态模块)
  • 日均 > 1000 ASIN 或需要多站点覆盖:Pangolinfo Amazon Scraper API,ROI 通常更优
相关文章
|
安全 前端开发 JavaScript
28、XSS常见payload
28、XSS常见payload
1645 0
|
网络协议 数据安全/隐私保护 Windows
当不在公司时,如何在外远程登录公司内网OA系统?
当不在公司时,如何在外远程登录公司内网OA系统?
952 0
|
Oracle Java 关系型数据库
idea配置jdk、淘宝镜像
idea配置jdk、淘宝镜像
1362 0
idea配置jdk、淘宝镜像
|
6月前
|
Web App开发 缓存 C++
Cursor 界面"结冰"了?!原因分析及解决方案
Cursor界面出现点状雪花样花屏,多因GPU硬件加速与显卡驱动兼容性问题所致。该现象常见于Electron/Chromium应用(如VS Code、Chrome等)。首选解决方案:在Runtime Arguments中启用`&quot;disable-hardware-acceleration&quot;: true`并重启。亦可尝试清理缓存、禁用插件、更新或回退显卡驱动。
734 3
|
5月前
|
SQL 人工智能 运维
很多 Agent 最后变成聊天框,问题出在哪?
不少 AI Agent 项目刚开始目标很大:自动查数据、调系统、处理流程。做着做着,却只剩一个能问答的窗口。原因通常不在模型本身,而在场景没拆清、工具没接稳、权限没管好、流程没跑通。
|
JSON API 数据安全/隐私保护
深度分析淘宝卖家订单详情API接口,用json返回数据
淘宝卖家订单详情API(taobao.trade.fullinfo.get)是淘宝开放平台提供的重要接口,用于获取单个订单的完整信息,包括订单状态、买家信息、商品明细、支付与物流信息等,支撑订单管理、ERP对接及售后处理。需通过appkey、appsecret和session认证,并遵守调用频率与数据权限限制。本文详解其使用方法并附Python调用示例。
|
7月前
|
数据采集 分布式计算 数据挖掘
跨境电商数据中台实践:亚马逊类目选品的六维决策模型落地
本文介绍面向跨境电商的亚马逊类目选品六维数据决策模型,融合BSR集中度、评论壁垒、新品速度等可解释指标,采用API+自建分析层架构(非黑盒SaaS),支持ASIN级实时分析与交叉筛选。已助力客户将新品胜率从32%提升至71%,年降沉没成本超400万元。(239字)
631 6
|
8月前
|
数据采集 JSON API
亚马逊数据采集 API 架构设计:同步 vs 异步的规模化实践
跨境电商数据平台面临同步采集吞吐瓶颈:1万ASIN同步需14小时,而异步架构通过任务解耦+并行处理,压缩至30~60分钟。响应延迟从5秒降至200ms,吞吐量可弹性扩展,积点成本不变,仅需增加轻量回调服务。适合日均百单以上规模化场景。(239字)
306 3
|
9月前
|
数据采集 人工智能 监控
Amazon竞品调价实时预警系统:OpenClaw AI Agent + Pangolinfo API 企业级落地实践
本方案为跨境电商打造实时竞品价格监控系统:通过Pangolinfo API每10分钟采集ASIN数据,OpenClaw AI Agent智能分析降价威胁并生成应对建议,飞书/Slack即时推送富文本告警。响应速度从24小时提升至10分钟(加速144倍),年ROI超10倍,开发仅需1–2天。(239字)
812 3

热门文章

最新文章