【问题标题】:How to prevent fake useragent detection in selenium headless?如何防止硒无头中的虚假用户代理检测?
【发布时间】:2021-05-06 20:56:39
【问题描述】:

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

我正在使用 selenium chromedriver。

【问题讨论】:

    标签: ruby selenium selenium-chromedriver user-agent botdetect


    【解决方案1】:

    请添加这些选项

        # 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多