简体   繁体   English

Selenium 3 python:为 Chrome DevTools 网络事件添加侦听器

[英]Selenium 3 python: add listener for Chrome DevTools network event

I am using Selenium 3 with python.我在 python 中使用Selenium 3 Currently it is possible to send a Chrome DevTools command using the execute_cdp_cmd binding:目前可以使用execute_cdp_cmd绑定发送Chrome DevTools命令:

from selenium import webdriver

driver = webdriver.Chrome()
response = driver.execute_cdp_cmd('Network.getAllCookies', {})
print(response)

Is it possible somehow to add a listener for aNetwork Event ?是否有可能以某种方式为网络事件添加侦听器? Something like:就像是:

driver.execute_cdp_cmd('Network.enable')
driver.add_listener('Network.dataReceived', my_listener)

It should be natively supported in Selenium 4 (currently in alpha), but I would like to know if it is possible to make this work in Selenium 3.它应该在 Selenium 4(目前处于 alpha 版)中得到本地支持,但我想知道是否有可能在 Selenium 3 中进行这项工作。

I think you can't do this in Selenium 3. In Selenium 3 add_listener doesn't look like the addListener in Java.我认为在 Selenium 3 中你不能这样做。在 Selenium 3 中add_listener看起来不像 Java 中的addListener Seems it only receives Console.ERROR Console.ALL and Console.Log as paramater.似乎它只接收Console.ERROR Console.ALLConsole.Log作为参数。

    @asynccontextmanager
    async def add_listener(self, event_type):
        '''
        Listens for certain events that are passed in.

        :Args:
         - event_type: The type of event that we want to look at.

         :Usage:
             ::

                async with driver.add_listener(Console.log) as messages:
                    driver.execute_script("console.log('I like cheese')")
                assert messages["message"] == "I love cheese"

        '''
        assert sys.version_info >= (3, 7)
        global cdp
        from selenium.webdriver.common.bidi.console import Console

        async with self._get_bidi_connection():
            global devtools
            session = cdp.get_session_context('page.enable')
            await session.execute(devtools.page.enable())
            session = cdp.get_session_context('console.enable')
            await session.execute(devtools.console.enable())
            console = {
                "message": None,
                "level": None
            }
            async with session.wait_for(devtools.console.MessageAdded) as messages:
                yield console
            if event_type == Console.ERROR:
                if messages.value.message.level == "error":
                    console["message"] = messages.value.message.text
                    console["level"] = messages.value.message.level
            elif event_type == Console.ALL:
                console["message"] = messages.value.message.text
                console["level"] = messages.value.message.level

Also, this seems not to be supported in Selenium 4 so far.此外,到目前为止,Selenium 4 似乎不支持这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM