自動化
Puppeteer 與 Playwright,直接連到你的設定檔
每個開啟的設定檔都有自己的偵錯位址。把你的程式碼連到那個設定檔上:它的指紋、它的 Cookie、它的代理都在。所有方案都包含,免費方案也一樣。
- 1在程式裡開啟本機介面:設定中的「本機 API」,複製金鑰。
- 2要求開啟一個設定檔。回傳的位址只屬於這個設定檔。
- 3像連線一般瀏覽器那樣,把你的程式碼連到這個位址。
- 4照常工作。指紋、Cookie 與代理都已經就位。
JavaScript (puppeteer-core)
const puppeteer = require('puppeteer-core');
(async () => {
// 1. Ask the app for this profile's debugging endpoint.
const started = await fetch(
'http://127.0.0.1:50325/api/v1/browser/start?profileId=YOUR_PROFILE_ID',
{ method: 'POST', headers: { 'x-api-token': 'YOUR_API_TOKEN' } },
).then((r) => r.json());
// 2. Attach to it like to any other browser.
const browser = await puppeteer.connect({
browserWSEndpoint: started.data.ws,
defaultViewport: null,
});
const [page] = await browser.pages();
await page.goto('https://example.com');
})();
Python (Playwright)
import requests
from playwright.sync_api import sync_playwright
# 1. Ask the app for this profile's debugging endpoint.
started = requests.post(
"http://127.0.0.1:50325/api/v1/browser/start",
params={"profileId": "YOUR_PROFILE_ID"},
headers={"x-api-token": "YOUR_API_TOKEN"},
).json()
# 2. Attach to it like to any other browser.
with sync_playwright() as p:
browser = p.chromium.connect_over_cdp(started["data"]["ws"])
page = browser.contexts[0].pages[0]
page.goto("https://example.com")
連線之前要知道的一件事
Puppeteer 與 Playwright 一連上就會自己開啟 Runtime.enable 與 Page.enable。這兩個網域會在 Chromium 內部裝上觀察器,而頁面指令碼能夠察覺。我們自己的腳本編排器從不開啟它們,所以由它驅動的設定檔與手動操作的一模一樣。如果你要打交道的網站會檢查這一點,就在程式裡編排步驟。