提交工单

香港服务器部署Headless Chrome爬虫:Playwright + 反检测 + IP轮换采集实战

文档更新于

现代电商平台(Amazon、TikTok Shop、速卖通)大量使用 JavaScript 动态渲染,传统 requests 爬虫只能获取空壳 HTML。Playwright 驱动真实 Chromium 浏览器执行 JS,可以获取完整渲染后的页面内容。香港服务器能直接访问 Amazon、eBay、TikTok Shop 等全球平台,是跨境电商数据采集的理想部署节点。


一、服务器环境准备

<code"># Ubuntu 22.04,推荐配置:2核4G(单浏览器实例约占 200~400MB)
apt update && apt install -y python3.12 python3.12-venv python3-pip

# 安装系统依赖(Playwright Chromium 需要)
apt install -y libglib2.0-0 libnss3 libnspr4 libatk1.0-0 \
  libatk-bridge2.0-0 libcups2 libdrm2 libdbus-1-3 libxkbcommon0 \
  libx11-6 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxrandr2 \
  libgbm1 libpango-1.0-0 libcairo2 libasound2

# 创建项目
mkdir -p /opt/scraper && cd /opt/scraper
python3.12 -m venv venv && source venv/bin/activate
pip install playwright playwright-stealth aiohttp redis asyncio

# 安装 Playwright 浏览器(只装 Chromium 节省空间)
playwright install chromium
playwright install-deps chromium

二、基础 Playwright 爬虫

<code">import asyncio
from playwright.async_api import async_playwright
from playwright_stealth import stealth_async

async def scrape_amazon_product(asin: str) -> dict:
    """抓取 Amazon 商品详情"""
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            args=[
                '--no-sandbox',
                '--disable-setuid-sandbox',
                '--disable-dev-shm-usage',     # 解决 Docker 内存问题
                '--disable-gpu',
                '--disable-web-security',
                '--lang=en-US',
            ]
        )

        context = await browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
            locale='en-US',
            timezone_id='America/New_York',
        )

        page = await context.new_page()

        # 应用反检测补丁(隐藏 webdriver 特征)
        await stealth_async(page)

        url = f"https://www.amazon.com/dp/{asin}"
        await page.goto(url, wait_until='domcontentloaded', timeout=30000)

        # 等待关键元素加载
        await page.wait_for_selector('#productTitle', timeout=10000)

        # 提取数据
        title = await page.locator('#productTitle').inner_text()
        price = await page.locator('.a-price .a-offscreen').first.inner_text()
        rating = await page.locator('.a-icon-alt').first.inner_text()

        # 提取评价数量
        review_count_el = page.locator('#acrCustomerReviewText')
        review_count = await review_count_el.inner_text() if await review_count_el.count() > 0 else "0"

        await browser.close()

        return {
            'asin': asin,
            'title': title.strip(),
            'price': price.strip(),
            'rating': rating.strip(),
            'review_count': review_count.strip(),
            'url': url,
        }

# 运行
result = asyncio.run(scrape_amazon_product("B0DGJXQV3F"))
print(result)

三、反检测进阶技巧

<code">async def create_stealth_context(playwright, proxy: str = None):
    """创建高度仿真的浏览器上下文"""
    browser = await playwright.chromium.launch(
        headless=True,
        args=['--no-sandbox', '--disable-dev-shm-usage']
    )

    # 代理配置(可选)
    proxy_config = None
    if proxy:
        host, port, user, passwd = proxy.split(':')
        proxy_config = {
            'server': f'http://{host}:{port}',
            'username': user,
            'password': passwd,
        }

    context = await browser.new_context(
        viewport={'width': 1366, 'height': 768},
        user_agent=random.choice(USER_AGENTS),
        locale='en-US',
        timezone_id='America/Los_Angeles',
        geolocation={'longitude': -118.4085, 'latitude': 33.9425},  # LA
        permissions=['geolocation'],
        proxy=proxy_config,
        # 设置额外 HTTP 头(模拟真实浏览器)
        extra_http_headers={
            'Accept-Language': 'en-US,en;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'DNT': '1',
        }
    )

    # 注入 JS 补丁:移除 webdriver 标识
    await context.add_init_script("""
        Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
        Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]});
        Object.defineProperty(navigator, 'languages', {get: () => ['en-US', 'en']});
        window.chrome = {runtime: {}};
    """)

    return browser, context

USER_AGENTS = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
]

四、批量并发采集(协程池)

<code">import asyncio
import random
from collections import deque

async def scrape_with_delay(page, url: str, min_delay=2, max_delay=5):
    """模拟人类访问节奏(随机延迟)"""
    await asyncio.sleep(random.uniform(min_delay, max_delay))
    await page.goto(url, wait_until='domcontentloaded', timeout=30000)

    # 模拟鼠标移动(随机滚动)
    await page.mouse.move(
        random.randint(100, 800),
        random.randint(100, 600)
    )
    await page.evaluate(f"window.scrollBy(0, {random.randint(200, 500)})")
    await asyncio.sleep(random.uniform(0.5, 1.5))

async def batch_scrape(asins: list[str], concurrency: int = 3) -> list[dict]:
    """并发采集(concurrency 控制同时运行的浏览器数量)"""
    semaphore = asyncio.Semaphore(concurrency)
    results = []

    async def scrape_one(asin):
        async with semaphore:
            try:
                result = await scrape_amazon_product(asin)
                results.append(result)
                print(f"✓ {asin}: {result['title'][:40]}")
            except Exception as e:
                print(f"✗ {asin}: {e}")

    tasks = [scrape_one(asin) for asin in asins]
    await asyncio.gather(*tasks)
    return results

# 使用示例
asins = ["B0DGJXQV3F", "B09G9FPHY6", "B08N5WRWNW"]
results = asyncio.run(batch_scrape(asins, concurrency=2))

五、Redis 任务队列(生产级采集系统)

<code">import redis
import json

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

class ScraperQueue:
    """基于 Redis 的分布式爬虫任务队列"""

    PENDING_KEY = "scraper:pending"
    DONE_KEY = "scraper:done"
    FAILED_KEY = "scraper:failed"

    def push_tasks(self, asins: list[str]):
        """批量加入待采集队列"""
        pipe = r.pipeline()
        for asin in asins:
            pipe.lpush(self.PENDING_KEY, asin)
        pipe.execute()
        print(f"已加入 {len(asins)} 个采集任务")

    async def run_worker(self, worker_id: int):
        """Worker 进程:从队列取任务,采集后写入 done"""
        print(f"Worker {worker_id} 启动")
        while True:
            asin = r.brpop(self.PENDING_KEY, timeout=5)
            if not asin:
                break    # 队列为空,退出
            _, asin = asin

            try:
                result = await scrape_amazon_product(asin)
                r.hset(self.DONE_KEY, asin, json.dumps(result))
                print(f"Worker {worker_id} ✓ {asin}")
            except Exception as e:
                r.lpush(self.FAILED_KEY, asin)
                print(f"Worker {worker_id} ✗ {asin}: {e}")

# 使用
queue = ScraperQueue()
queue.push_tasks(["B0DGJXQV3F", "B09G9FPHY6"])

# 启动多个 Worker(可分布到多台香港服务器)
asyncio.run(queue.run_worker(1))

六、Docker 容器化部署

<code">FROM python:3.12-slim

# 安装 Chromium 依赖
RUN apt-get update && apt-get install -y \
    libglib2.0-0 libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 \
    libcups2 libdrm2 libdbus-1-3 libxkbcommon0 libx11-6 \
    libxcomposite1 libxdamage1 libxext6 libxfixes3 libxrandr2 \
    libgbm1 libpango-1.0-0 libcairo2 libasound2 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
RUN playwright install chromium && playwright install-deps chromium

COPY . .
CMD ["python", "main.py"]

七、总结

香港服务器 + Playwright 是跨境电商数据采集的黄金组合:直连 Amazon/TikTok Shop 等全球平台无需代理,CN2 GIA 线路保证采集速度稳定。配合 Redis 任务队列,可以横向扩展到多台服务器并行采集,轻松支撑每天万级商品的价格和排名监控。

需要服务器?

香港 / 美国 / 日本服务器与 VPS,工程师 7×24 在线,工单平均 10 分钟内响应。