如何在 Playwright 中設定 Proxy(瀏覽器全域與 Per-Context 驗證)
更新於:
Playwright 原生支援 HTTP 代理驗證(server、username、password),適用於 Chromium、Firefox 與 WebKit,完全不需要安裝瀏覽器擴充功能或第三方套件。更優異的是,Playwright 的 Per-Context Proxy(獨立上下文代理)功能可讓單一瀏覽器實例同時執行數十個相互隔離的 BrowserContext 工作階段,各自綁定專屬的 VinaProxy 靜態 IP。
proxy={ server: 'http://ip:port', username: 'user', password: 'pass' }- 1 個IP₫40,000
- 5+ 個IP₫35,000
- 10+ 個IP₫25,000
- 20+ 個IP₫25,000
- 50+ 個IP₫25,000
- 100+ 個IP₫25,000
- 200+ 個IP₫25,000
- 500+ 個IP₫25,000
- 1000+ 個IP₫22,000
- 2000+ 個IP₫20,000
- 1 個IP₫50,000
- 3+ 個IP₫40,000
- 5+ 個IP₫40,000
- 10+ 個IP₫32,000
- 50+ 個IP₫30,000
- 100+ 個IP₫30,000
- 200+ 個IP₫30,000
- 500+ 個IP₫25,000
Playwright proxy 物件參數設定
無論是在 chromium.launch({ proxy }) 中進行全域設定,還是在 browser.newContext({ proxy }) 中為個別工作階段設定,皆傳入標準的 proxy 物件:
| Playwright 屬性 | 數值格式 | 技術說明 |
|---|---|---|
server | 'http://ip:port' | 僅填寫主機與連接埠,前面必須加上 http:// |
username | 'user' | VinaProxy 後台提供的 Proxy 使用者名稱 |
password | 'pass' | Proxy 密碼(Playwright 會自動處理 HTTP 407 驗證挑戰) |
bypass | 'localhost,127.0.0.1' | 選填參數,以逗點分隔略過代理的主機清單 |
高效運作多 IP BrowserContext 的最佳實踐
- 在 Windows 與 macOS 上,若要在各別
browser.newContext()中指派不同的proxy,必須在chromium.launch()中加入預留參數proxy: { server: 'http://per-context' }啟動 Chromium 路由 - 在
browser.newContext()中將timezoneId與locale設定為與 Proxy 所在國家一致,確保標頭與 JavaScriptIntlAPI 符合當地特徵 - 使用
page.route()攔截並中止非必要的圖片與字型資源載入,大幅提升爬蟲擷取速度
操作步驟
- 1
取得 IP、Port、使用者名稱與密碼
從 VinaProxy 控制面板複製
ip:port:user:pass連線認證資訊。 - 2
將 proxy 物件帶入 newContext()
呼叫
const context = await browser.newContext({ proxy: { server: 'http://ip:port', username: 'user', password: 'pass' } })。 - 3
同步時區 timezoneId 與語系 locale
填入與代理 IP 所在地理位置相對應的
timezoneId與locale(如America/New_York或Asia/Ho_Chi_Minh)。 - 4
在新分頁中檢查出口 IP
開啟新頁面
const page = await context.newPage()並發送請求至https://vinaproxy.com/api/my-ip驗證對外 IP。
常見問題
為什麼 Playwright 出現 'Proxy is only supported when browser is launched with a proxy' 錯誤?
在 Windows 與 macOS 平台上,Chromium 需要在啟動時指定全域 Proxy 參數,才能允許在個別 Context 中進行覆寫。請使用 chromium.launch({ proxy: { server: 'http://per-context' } }) 啟動瀏覽器,接著再將實際 Proxy 傳入各個 browser.newContext({ proxy })。
Playwright 的 Firefox 與 WebKit 也相容 VinaProxy 代理嗎?
是的。在 Node.js 與 Python 中,Chromium、Firefox 以及 WebKit 皆採用完全一致的 proxy: { server, username, password } 語法。
以無頭模式執行 Playwright 會計算流量費用嗎?
不會。所有 VinaProxy 專屬 IPv4 與靜態 ISP 方案均享有每月無限流量。
透過專屬靜態 IP 大幅擴展 Playwright BrowserContext
涵蓋全球 7 大地區、無限流量的高速 HTTP(S) 靜態代理。
購買 Playwright Proxy