如何在 Playwright 中添加自定义 headers

How to add custom headers in Playwright

headers["user-agent"] = fakeUa();
  console.log(fakeUa())
  let firstReq = true;
    page.route('**/*', route => {
    const request = route.request()
    //console.log(request.url(), JSON.stringify(request.headers()));
    
    if("x-j3popqvx-a" in request.headers()){
        headers = request.headers();
        //console.log(headers);
        console.log("exiting");
        return;
    }
    else {
        console.log("in");
        return route.continue({headers: headers});
    }
  });
  let pageRes = await page.goto(url, {waitUntil: 'load', timeout: 0});

我想在向 url 发送请求时添加假用户代理。但它不添加假用户代理,而是使用默认用户代理。

puppeteer it was possible with the page.setUserAgent() method to apply a custom UA and page.setExtraHTTPHeaders() to set any custom headers, in playwright you can set custom user agent (userAgent) and headers (extraHTTPHeaders) as options of browser.newPage() or browser.newContext() 喜欢:

const page = await browser.newPage({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36' })
const page = await browser.newPage({ extraHTTPHeaders: 'Cache-Control': 'no-cache' })

编辑: 如果您将它与 newContext() 一起使用,用法如下所示(确保在 [=21] 的设置中设置 userAgent =] 而不是 newPage!):

const context = await browser.newContext({ userAgent: 'hello' })
const page = await context.newPage()
// to check the UA:
console.log(await page.evaluate(() => navigator.userAgent))