更改 puppeteer-extra 上的用户代理似乎没有生效

Lio*_*oRz 7 user-agent chromium typescript puppeteer

我正在尝试使用 puppeteer 抓取不同的网站。由于我使用puppeteer-extra(对于他们的Stealth-plugin),我决定使用他们的anonymize-ua 插件来随机更改默认用户代理以进一步减少检测。

我尝试按照他们的解释进行操作,但是当我记录浏览器的实际用户代理时,它似乎没有生效。

下面附上我正在做的一个例子:

import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import UserAgent from 'user-agents';

const scrape = async (url: string) => {
    // Set stealth plugin
    const stealthPlugin = StealthPlugin();
    puppeteer.use(stealthPlugin);

    // Create random user-agent to be set through plugin
    const userAgent = new UserAgent({ platform: 'MacIntel', deviceCategory: 'desktop' });
    const userAgentStr = userAgent.toString();
    console.log(`User Agent: ${userAgentStr}`);

    const anonymizeUserAgentPlugin = require('puppeteer-extra-plugin-anonymize-ua')({
        customFn: () => userAgentStr 
    });
    puppeteer.use(anonymizeUserAgentPlugin);

    puppeteer
        .launch({ headless: false })
        .then(async (browser) => {
            // Different from the one above
            console.log(`User Agent: ${await browser.userAgent()}`);
        })
        .catch((e) => console.log(e));
}
Run Code Online (Sandbox Code Playgroud)

尽管第一个用户代理字符串是通过用户代理库随机化的(从运行到运行) ,但创建浏览器时记录的另一个是实际运行的 Chromium 版本。

我是否缺少某些配置?或者我不应该像这样查看浏览器用户代理吗?

Lio*_*oRz 4

经过深入研究puppeteer-extra和 anonymize-ua 插件代码,我发现:

  1. 用户代理在page实例上已更改,因此尝试查看来自的用户代理browser不会导致实际使用的用户代理。navigator.useragent正确的方法是通过 devtools 控制台登录。
  2. puppeteer 上存在一个未解决的问题,即事件没有足够早地触发,以便侦听器(例如使用 的插件onPageCreated)能够在浏览器请求发生之前修改页面实例(例如用户代理)。看来他们首先尝试通过goto about:blank来解决这个问题。这个解决方法并没有为我解决这个问题,因为用户代理没有改变。

所以我的解决方案是复制插件中的代码并在以下位置设置生成的用户代理page

puppeteer
    .launch({ headless: false })
    .then(async (browser) => {
        browser
            .pages()
            .then(async ([page]) => {
                await page.setUserAgent(userAgentStr);
            })
            .catch(async (e) => {
                console.log(e);
                await browser.close();
            });
    })
    .catch((e) => console.log(e));
Run Code Online (Sandbox Code Playgroud)

希望这对任何人都有帮助!