Python中的Selenium移除window.navigator.webdriver

移除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')

  1. CPD 的官方文档: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-addScriptToEvaluateOnNewDocument ↩︎

  2. Selenium官方文档: https://www.selenium.dev/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.webdriver.html#selenium.webdriver.chrome.webdriver.WebDriver.execute_cdp_cmd ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值