问题描述
我正在以无头模式运行抓取机器人。如您所知,当它在无头模式下运行时,它在 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