Selenium 3 python: add listener for Chrome DevTools network event

2k views Asked by At

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.

1

There are 1 answers

0
Sherry869 On

I think you can't do this in Selenium 3. In Selenium 3 add_listener doesn't look like the addListener in Java. Seems it only receives Console.ERROR Console.ALL and Console.Log as paramater.

    @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.