Proxy Port logo
如何 操作指南 > 如何为 Playwright 设置代理

如何为 Playwright 设置代理

文章为希望通过 Playwright 使用代理的任何人提供了有用的信息,并提供了一些关于选择正确方法的好建议。

有多种方法可以为 Playwright 设置代理。

如果您正在使用 Playwright 进行网页抓取,那么使用 Crawlee 框架可能会更好,它简化了蜘蛛开发过程并包含一组 使用代理的工具


如果您需要直接在 Playwright 中设置代理,您可以在两个级别上执行此操作:浏览器级别和上下文级别。 让我们根据您的特定需求和用例按顺序考虑所有选项。
浏览器级别
Python
Node.js
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(
        proxy={
            "server": "http://127.0.0.1:8080"
        }
    )
    response = browser.new_context().request.get(
        "https://example.com",
        timeout=5000
    )
    print(response.body())

            
        
import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch({
    proxy: {server: 'http://127.0.0.1:8080'}
  });
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('https://example.com/');

  console.log(await page.content());

  await context.close();
  await browser.close();
})()

            
        
上下文级别
Python
Node.js
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(proxy={
        "server": "http://127.0.0.1:8080"
    })
    response = context.request.get(
        "https://example.com",
        timeout=5000
    )
    print(response.body())


            
        
import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext({
    proxy: {server: 'http://127.0.0.1:8080'}
  });
  const page = await context.newPage();

  await page.goto('https://example.com/');

  console.log(await page.content());

  await context.close();
  await browser.close();
})()
            
        
抓取代理
了解更多