3

I am using Selenium 3 with python. Currently it is possible to send a Chrome DevTools command using the execute_cdp_cmd binding:

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 a Network 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.

4

1 回答 1

0

我认为你不能在 Selenium 3 中做到这一点。在 Selenium 3add_listener中看起来不像addListener在 Java 中。似乎它只接收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

此外,到目前为止,这似乎在 Selenium 4 中不受支持。

于 2021-02-22T14:35:48.523 回答