如何为 Playwright 设置代理
文章为希望通过 Playwright 使用代理的任何人提供了有用的信息,并提供了一些关于选择正确方法的好建议。
有多种方法可以为 Playwright 设置代理。
如果您需要直接在 Playwright 中设置代理,您可以在两个级别上执行此操作:浏览器级别和上下文级别。 让我们根据您的特定需求和用例按顺序考虑所有选项。
浏览器级别
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();
})()
上下文级别
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();
})()