Skip to main content

Examples

The (Selenium) examples below are assuming that all prerequisites are met and you have successfully initiated the webdriver.

CDP API

The CDP API provides automatically generated classes (based on CDP domains) and bindings to respective methods and events. Below two examples, are listed. The full reference is available on the Chrome DevTools Protocol website

note

Selenium has stated in their reference that they will eventually move away from CDP, hence they suggest using the agnostic BiDi API, which abstracts away the implementation details of CDP.

By setting cookies (e.g. for user preferences), you can test how your website behaves with different configurations.

async with driver.bidi_connection() as connection:
execution = connection.devtools.network.set_cookie(
name="cheese",
value="gouda",
domain="www.selenium.dev",
secure=True
)

await connection.session.execute(execution)

See also alternative implementations

Basic Auth

Basic Auth allows you to test websites that have basic access authentication implemented.

async with driver.bidi_connection() as connection:
await connection.session.execute(connection.devtools.network.enable())

credentials = base64.b64encode("admin:admin".encode()).decode()
auth = {'authorization': 'Basic ' + credentials}

await connection.session.execute(connection.devtools.network.set_extra_http_headers(Headers(auth)))

See also alternative implementations

BiDi API

While the BiDi API is currently implemented with CDP, the same bindings are compatible with the WebDriver-BiDi Protocol, which is being implemented on a feature basis. See the full reference on the WebDriver-BiDi Protocol website

Console Logs

Listening to console events by type / level allows you to process them further.

async with driver.bidi_connection() as session:
log = Log(driver, session)

async with log.add_listener(Console.ALL) as messages:

See also alternative implementations

Network Interception

Network events can be intercepted for both requests and responses in order to consume or transform them.

async with driver.bidi_connection() as connection:
await connection.session.execute(connection.devtools.network.enable())
listener = connection.session.listen(connection.devtools.network.ResponseReceived)

content_types = []
async with listener:
async for event in listener:
content_types.append(event.response.headers["content-type"])
if "text/html; charset=utf-8" in content_types:
break

See also alternative implementations or WebdriverIO reference on CDP