迁移浏览器执行环境
使用 puppeteer-core 连接时无需为此流程安装本地 Chromium;应用仍需运行并组织自动化脚本。
01 / 产品介绍
AdsCrawl 通过 Remote CDP API 提供 Puppeteer 云浏览器。创建会话并发现 WebSocket 调试地址后,使用 puppeteer.connect 将现有 Node.js 脚本连接到远程浏览器。
远程 CDP 浏览器:了解为 Puppeteer 提供连接地址的临时会话生命周期。
Playwright 云浏览器:已有自动化代码使用 Playwright 时,查看对应客户端的连接示例。
02 / 适用场景
使用 puppeteer-core 连接时无需为此流程安装本地 Chromium;应用仍需运行并组织自动化脚本。
使用 Puppeteer 导航、读取页面和获取结果;迁移前检查本地文件、扩展与浏览器版本等依赖。
为任务创建临时会话,在 finally 中释放,并保留会话 ID 以便失败后清理。
03 / 快速开始
需要支持 fetch 的 Node.js 和 puppeteer-core(npm install puppeteer-core),保存为 .mjs 文件。 先在服务端设置 ADSCRAWL_API_KEY 环境变量。
完整参数与响应说明 →import puppeteer from "puppeteer-core";
const base = "https://api.adscrawl.net";
const headers = {
"x-api-key": process.env.ADSCRAWL_API_KEY,
"content-type": "application/json",
};
const response = await fetch(base + "/cdp/sessions", {
method: "POST", headers,
body: JSON.stringify({ idleTimeoutMs: 600000 }),
});
if (!response.ok) throw new Error("Create session failed: HTTP " + response.status);
const session = await response.json();
if (typeof session.sessionId !== "string" || !session.sessionId) {
throw new Error("Create response is missing sessionId");
}
try {
if (typeof session.cdpBaseUrl !== "string" || !session.cdpBaseUrl) {
throw new Error("Create response is missing cdpBaseUrl");
}
const discovery = new URL(session.cdpBaseUrl);
discovery.pathname = discovery.pathname.replace(/\/+$/, "") + "/json/version";
const version = await fetch(discovery);
if (!version.ok) throw new Error("CDP discovery failed: HTTP " + version.status);
const { webSocketDebuggerUrl } = await version.json();
if (typeof webSocketDebuggerUrl !== "string" || !webSocketDebuggerUrl) {
throw new Error("Discovery response is missing webSocketDebuggerUrl");
}
const browser = await puppeteer.connect({
browserWSEndpoint: webSocketDebuggerUrl,
});
try {
const page = await browser.newPage();
await page.goto("https://www.adscrawl.net");
const title = await page.title();
// Use title in your application; keep page content and session URLs out of logs.
} finally {
await browser.disconnect();
}
} finally {
const stopped = await fetch(base + "/cdp/sessions/" + encodeURIComponent(session.sessionId), {
method: "DELETE", headers,
});
if (!stopped.ok) throw new Error("Session cleanup failed: HTTP " + stopped.status);
}API Key 仅保存在服务端。遇到 HTTP 402 请检查额度,遇到 429 请降低并发并退避重试。
05 / FAQ
远程浏览器已经启动,应使用 puppeteer.connect;puppeteer.launch 会在自己的环境中启动浏览器进程。
示例中的远程连接不需要;puppeteer-core 提供客户端,Chromium 由 AdsCrawl 运行。
不能,需要创建新的临时会话。保存浏览器配置属于独立的云浏览器 API 流程。