当我们使用selenium 去访问或爬取某些网站的时候会遇到网站对selenium检测的一些情况。
正常用浏览器访问时:window.navigator属性是undefind
而使用selenium去访问 则会给window.navigator 设置webdriver属性
处理方法:
1.可以使用CDP(chrome开发者工具协议)解决这个问题
利用它可以实现每个页面刚加载的时候就执行Javascript语句 将webdriver属性置空
from selenium import webdriver
from selenium.webdriver import ChromeOptions
# 方法1 在每次打开新的页面时将webdriver属性置为空
option = ChromeOptions()
option.add_argument('--disable-blink-features=AutomationControlled')
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=option, executable_path="chromedriver.exe")
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
"source": 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
})
# 方法2
option = ChromeOptions()
option.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Chrome(options=option, executable_path="chromedriver.exe")
driver.get("xxxxxx")
还有一种方法是stealth.min.js
with open('stealth.min.js') as f:
js = f.read()
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": js
})
不过该方式有时候也会被检测出来