Skip to content

Playing with CDP

Target page: https://slensky.com/zendriver-examples/console.html

In this tutorial, we will explore how to use the Chrome DevTools Protocol (CDP) directly, when Zendriver does not provide a specific API for the functionality you need.

Sending CDP commands

To start using CDP, we first need to create a new script for the tutorial. In this example, we will send a command to enable the runtime domain.

import asyncio

import zendriver as zd
from zendriver import cdp
from zendriver.cdp import runtime


async def main() -> None:
    browser = await zd.start()
    page = await browser.get(
        "https://slensky.com/zendriver-examples/console.html",
    )

    # Those 2 lines are equivalent and do the same thing
    await page.send(runtime.enable())
    await page.send(cdp.runtime.enable())

    await browser.stop()


if __name__ == "__main__":
    asyncio.run(main())

Listening to CDP events

Now, let's listen to some CDP events. In this example, we will listen to console messages and print them out.

import asyncio

import zendriver as zd
from zendriver import cdp
from zendriver.cdp import runtime


async def main() -> None:
    browser = await zd.start()
    page = await browser.get(
        "https://slensky.com/zendriver-examples/console.html",
    )

    # Those 2 lines are equivalent and do the same thing
    await page.send(runtime.enable())
    await page.send(cdp.runtime.enable())

    def console_handler(event: cdp.runtime.ConsoleAPICalled) -> None:
        joined_args = ", ".join([str(it.value) for it in event.args])
        print(f"Console message: {event.type_} - {joined_args}")

    # Those 2 lines are equivalent and do the same thing
    page.add_handler(runtime.ConsoleAPICalled, console_handler)
    page.add_handler(cdp.runtime.ConsoleAPICalled, console_handler)

    await (await page.select("#myButton")).click()
    await page.wait(1) # Wait for the console messages to be printed

    # Remember to remove handlers to stop listening to console events
    page.remove_handlers(runtime.ConsoleAPICalled, console_handler)
    page.remove_handlers(cdp.runtime.ConsoleAPICalled, console_handler)

    await browser.stop()


if __name__ == "__main__":
    asyncio.run(main())