如何防止selenium headless中的虚假用户代理检测?

How to prevent fake useragent detection in selenium headless?

我是运行一个无头模式的抓取机器人。如您所知,当它在无头模式下为 运行 时,它在用户代理中包含无头字符串。为避免该问题,我更改了用户代理。该网站检测到这个虚假的用户代理并阻止了抓取机器人。我怎样才能防止这种检测?

我正在使用 selenium chromedriver。

请添加这些选项

    # windows_useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36"
    # linux_useragent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36"
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_argument("--no-sandbox")
    options.add_argument("user-agent=#{linux_useragent}")
    options.add_argument("--disable-web-security")
    options.add_argument("--disable-xss-auditor")
    options.add_option("excludeSwitches", ["enable-automation", "load-extension"])

navigator.platform 和 navigator.userAgent 应该匹配。

如果 userAgent 用于 windows,则 navigator.platform 应为“Win32”

如果 userAgent 用于 linux,那么 navigator.platform 应该是“Linux x86_64”

你可以这样设置

platform = {
  windows: "Win32",
  linux: "Linux x86_64"
}
driver.execute_cdp("Page.addScriptToEvaluateOnNewDocument", {
  "source": "
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    }),
    Object.defineProperty(navigator, 'languages', {
      get: () => ['en-US', 'en']
    }),
    Object.defineProperty(navigator, 'platform', {
      get: () => \"#{platform[:linux]}\"
    })"
})

当然你需要将 navigator.webdriver 设置为 undefined