抓取动态网站

动态网站在初始页面加载后使用 JavaScript 加载内容。本指南介绍如何使用 FourA 的 browser endpoint 从这些网站收集数据。

问题

当您向大量使用 JavaScript 的网站发送标准 HTTP request 时,您只能获取 HTML 外壳,而无法获取实际内容。您需要的数据(商品列表、价格、搜索结果)是在页面在浏览器中渲染后由 JavaScript 加载的。

这在 React、Vue、Angular 和 Next.js 等现代框架中越来越常见。

解决方案:Browser Requests

FourA 的 browser endpoint (POST /api/browser/) 会在 Chrome 浏览器实例中打开您的 URL,该实例会:

  1. 加载页面
  2. 执行所有 JavaScript
  3. 等待内容渲染
  4. 返回完全渲染后的 HTML

步骤 1:确定您需要的内容

在发送 request 之前,请在浏览器中访问目标页面,并使用 DevTools (F12) 找到一段文本或元素,以确认内容已加载。例如:

  • JS 渲染后出现的商品名称
  • 渲染后的 HTML 中类似于 product-grid 的 CSS 类
  • 仅在数据加载时才出现的文本字符串(如 "results")

步骤 2:发送 Browser Request

curl -X POST https://eu.api.foura.ai/api/browser/ \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/products",
    "timeout_ms": 15000,
    "checkText": "product-grid"
  }'

checkText 选项指示 FourA 验证渲染后的页面中是否出现字符串 "product-grid"。如果该字符串未在超时前出现,则 request 失败,从而让您知道内容未加载。

步骤 3:解析 HTML

response 的 body 字段中包含完全渲染后的 HTML。使用您首选的库进行解析:

Python (BeautifulSoup)

import requests
from bs4 import BeautifulSoup

resp = requests.post("https://eu.api.foura.ai/api/browser/", headers={
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}, json={
    "url": "https://example.com/products",
    "timeout_ms": 15000,
    "checkText": "product-grid"
})

html = resp.json()["body"]
soup = BeautifulSoup(html, "html.parser")

for product in soup.select(".product-card"):
    name = product.select_one(".product-name").text.strip()
    price = product.select_one(".product-price").text.strip()
    print(f"{name}: {price}")

Node.js (cheerio)

import * as cheerio from 'cheerio';

const resp = await fetch('https://eu.api.foura.ai/api/browser/', {
  method: 'POST',
  headers: { 'X-API-Key': 'YOUR_API_KEY', 'Content-Type': 'application/json' },
  body: JSON.stringify({
    url: 'https://example.com/products',
    timeout_ms: 15000,
    checkText: 'product-grid'
  })
});

const { body: html } = await resp.json();
const $ = cheerio.load(html);

$('.product-card').each((i, el) => {
  console.log($(el).find('.product-name').text(), $(el).find('.product-price').text());
});

故障排除

仍然获取到空内容?

  • 验证页面是否确实使用 JavaScript 渲染(对比“查看网页源代码”与 DevTools)
  • 增加 timeout_ms:某些页面加载较慢
  • 检查页面是否需要身份验证或 cookie(使用 cookies 参数)

遇到 CAPTCHA 页面?

  • 对于单次/HTTP request,请切换到 proxy endpoint (POST /api/proxy/) 以进行自动 IP 轮换。
  • 若要为 browser request 添加 proxy 轮换,请使用 browser endpoint 的 proxy 参数,而不是将其嵌套在 proxy endpoint 中。proxy endpoint 仅封装单次/HTTP request,不封装 browser request。
curl -X POST "https://eu.api.foura.ai/api/browser/" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com", "proxy": "http://proxy-url:port"}'

后续步骤

更新于: 2026年5月31日