Use this file to discover all available pages before exploring further.
Zendriver provides full access to the Chrome DevTools Protocol (CDP) through the cdp module. This allows you to control the browser at the lowest level and access features not exposed through the high-level API.
CDP commands are sent using the send() method on a Connection (or Tab/Browser):
# Navigate to a URLawait tab.send(cdp.page.navigate(url="https://example.com"))# Execute JavaScriptresult = await tab.send( cdp.runtime.evaluate( expression="document.querySelector('h1').textContent", return_by_value=True ))print(result.value) # Prints the h1 text# Take a screenshotscreenshot = await tab.send( cdp.page.capture_screenshot(format_="png"))with open("screenshot.png", "wb") as f: f.write(base64.b64decode(screenshot))
# Navigate and wait for loadawait tab.send(cdp.page.navigate(url="https://example.com"))await tab.send(cdp.page.enable())await tab.wait() # Wait for page to be idle# Wait for specific lifecycle eventawait tab.send(cdp.page.set_lifecycle_events_enabled(enabled=True))# Add handler for load eventtab.add_handler(cdp.page.LifecycleEvent, lambda e: print(e.name))
# Emulate mobile deviceawait tab.send( cdp.emulation.set_device_metrics_override( width=375, height=667, device_scale_factor=2, mobile=True ))# Set user agentawait tab.send( cdp.emulation.set_user_agent_override( user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)" ))# Set geolocationawait tab.send( cdp.emulation.set_geolocation_override( latitude=37.7749, longitude=-122.4194, accuracy=100 ))
Many CDP domains emit events that you can listen to:
import zendriver.cdp as cdp# Enable domain to receive eventsawait tab.send(cdp.network.enable())# Add handler for specific eventtab.add_handler(cdp.network.RequestWillBeSent, lambda e: print(e.request.url))# Add handler for all events in a domaintab.add_handler(cdp.network, lambda e: print(f"Network event: {e}"))# Async handlersasync def handle_console(event): print(f"Console {event.type}: {event.text}")await tab.send(cdp.runtime.enable())tab.add_handler(cdp.runtime.ConsoleAPICalled, handle_console)