如何在Puppeteer中设置多个自定义HTTP标头?

12

我正在尝试使用Puppeteer登录https://kith.com/account/login?return_url=%2Faccount。当我登录并使用音频解决验证码时,它将我识别为一个机器人,因此我尝试更改请求标头以查看是否有所帮助,但找不到任何关于如何更改标头的信息。

我找到了这个,但它只显示了一个标头:

await page.setRequestInterception(true)

        page.on('request', (request) => {
            const headers = request.headers();
            headers['X-Just-Must-Be-Request-In-All-Requests'] = '1';
            request.continue({
                headers
            });
        });
2个回答

32

通过专用的Puppeteer方法page.setExtraHTTPHeaders,您可以设置多个HTTP标头。

E.g.:

await page.setExtraHTTPHeaders({
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
        'upgrade-insecure-requests': '1',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'en-US,en;q=0.9,en;q=0.8'
    })
await page.goto('...')

2
是一个数组,您可以添加任意数量的元素。
 page.on('request', (request) => {
            const headers = request.headers();
            headers['X-Just-Must-Be-Request-In-All-Requests'] = '1';
            headers['foo'] = 'bar';
            headers['foo2'] = 'bar2';
            
            request.continue({
                headers
            });
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接