微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何防止硒无头中的虚假用户代理检测?

如何解决如何防止硒无头中的虚假用户代理检测?

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

我正在使用 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']
    }),'platform',{
      get: () => \"#{platform[:linux]}\"
    })"
})

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。