
一、核心痛点
亚马逊关联商品(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 通常更优