移除window.navigator.webdriver需要使用 Google 的Chrome Devtools-Protocol(Chrome 开发工具协议)简称 CDP1。
Selenium支持使用CDP2。如果是在本地调试,可以参照https://www.cnblogs.com/presleyren/p/12936553.html 这位大神的写法。
本地初始化方式
chromeOptions = webdriver.ChromeOptions()
# chromeOptions.add_argument('-headless') # 设为无头模式
# chromeOptions.add_argument('--user-agent=Mozilla/5.0 HAHA') # 配置对象添加替换User-Agent的命令
chromeOptions.add_argument('--disable-infobars') # 去掉提示:Chrome正收到自动测试软件的控制
chromeOptions.add_experimental_option('excludeSwitches', ['enable-automation'])
chromeOptions.add_experimental_option('useAutomationExtension', False)
chromeOptions.add_argument('--start-maximized') # 最大化运行(全屏窗口),不设置,取元素会报错
with webdriver.Chrome(options=chromeOptions) as driver:
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
})
driver.get('https://xxxxxxxxxx')
但我这里是部署了Selenium Grid集群,连接集群的客户端driver是没有execute_cdp_cmd这个函数的。通过阅读源代码发现,所有的调用过程其实是通过Http方式调用,使用的是同一个接口,要使用远程某个功能,就可以将功能名当作参数发送出去。
逻辑为:
def execute_cdp_cmd(self, cmd, cmd_args):
"""
Execute Chrome Devtools Protocol command and get returned result
The command and command args should follow chrome devtools protocol domains/commands, refer to link
https://chromedevtools.github.io/devtools-protocol/
:Args:
- cmd: A str, command name
- cmd_args: A dict, command args. empty dict {} if there is no command args
:Usage:
driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})
:Returns:
A dict, empty dict {} if there is no result to return.
For example to getResponseBody:
{'base64Encoded': False, 'body': 'response body string'}
"""
return self.execute("executeCdpCommand", {'cmd': cmd, 'params': cmd_args})['value']
所以,如果你使用了远程Grid集群,则初始化代码为:
chromeOptions = webdriver.ChromeOptions()
# chromeOptions.add_argument('-headless') # 设为无头模式
# chromeOptions.add_argument('--user-agent=Mozilla/5.0 HAHA') # 配置对象添加替换User-Agent的命令
chromeOptions.add_argument('--disable-infobars') # 去掉提示:Chrome正收到自动测试软件的控制
chromeOptions.add_experimental_option('excludeSwitches', ['enable-automation'])
chromeOptions.add_experimental_option('useAutomationExtension', False)
chromeOptions.add_argument('--start-maximized') # 最大化运行(全屏窗口),不设置,取元素会报错
with webdriver.Remote(command_executor=
ChromeRemoteConnection(
remote_server_addr='http://remotehost:5555/wd/hub',
keep_alive=True),
desired_capabilities={
'platform': 'ANY',
'browserName': "chrome",
'version': '',
'javascriptEnabled': True
},
options=chromeOptions
) as driver:
print(driver.execute("executeCdpCommand", {'cmd': "Page.addScriptToEvaluateOnNewDocument", 'params': {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
}}))
driver.get('https://xxxxxxxxxx')