Skip to content

Tab

Drives a single browser tab: navigation, finding elements, input, screenshots, events, and network. Learn more in Core concepts.

pydoll.browser.tab.Tab

Tab(browser, connection_port=None, target_id=None, browser_context_id=None, ws_address=None, connection_handler=None)

Bases: FindElementsMixin

Controls a browser tab via Chrome DevTools Protocol.

Primary interface for web page automation including navigation, DOM manipulation, JavaScript execution, event handling, network monitoring, and specialized tasks like Cloudflare Turnstile handling.

Initialize tab controller for existing browser tab.

PARAMETER DESCRIPTION
browser

Browser instance that created this tab.

TYPE: Browser

connection_port

CDP WebSocket port.

TYPE: int | None DEFAULT: None

target_id

CDP target identifier for this tab.

TYPE: str | None DEFAULT: None

browser_context_id

Optional browser context ID.

TYPE: str | None DEFAULT: None

ws_address

Optional WebSocket address for this tab.

TYPE: str | None DEFAULT: None

connection_handler

Pre-built connection handler; created from connection details when omitted (mainly for testing).

TYPE: ConnectionHandler | None DEFAULT: None

target_id property

target_id

CDP target id of this tab, when known.

browser_context_id property

browser_context_id

Browser context this tab belongs to (None for the default context).

page_events_enabled property

page_events_enabled

Whether CDP Page domain events are enabled.

network_events_enabled property

network_events_enabled

Whether CDP Network domain events are enabled.

fetch_events_enabled property

fetch_events_enabled

Whether CDP Fetch domain events (request interception) are enabled.

dom_events_enabled property

dom_events_enabled

Whether CDP DOM domain events are enabled.

runtime_events_enabled property

runtime_events_enabled

Whether CDP Runtime domain events are enabled.

request property

request

Get the request object for making HTTP requests using the browser's fetch API.

RETURNS DESCRIPTION
Request

An instance of the Request class for making HTTP requests.

TYPE: Request

scroll property

scroll

Get the scroll API for controlling page scroll behavior.

RETURNS DESCRIPTION
ScrollAPI

An instance of the ScrollAPI class for scroll operations.

TYPE: ScrollAPI

keyboard property

keyboard

Get the keyboard API for controlling keyboard input at page level.

RETURNS DESCRIPTION
KeyboardAPI

An instance of the KeyboardAPI class for keyboard operations.

TYPE: KeyboardAPI

mouse property

mouse

Get the mouse API for controlling mouse input.

RETURNS DESCRIPTION
MouseAPI

An instance of the MouseAPI class for mouse operations.

TYPE: MouseAPI

intercept_file_chooser_dialog_enabled property

intercept_file_chooser_dialog_enabled

Whether file chooser dialog interception is active.

extract async

extract(model, *, scope=None, timeout=0)

Extract structured data from the page into a typed model.

PARAMETER DESCRIPTION
model

ExtractionModel subclass defining the extraction schema.

TYPE: type[T]

scope

Optional CSS/XPath selector to limit extraction region.

TYPE: str | None DEFAULT: None

timeout

Seconds to wait for elements (0 = no wait).

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
T

Populated model instance with extracted data.

RAISES DESCRIPTION
FieldExtractionFailed

If a required field cannot be extracted.

InvalidExtractionModel

If model definition is invalid.

extract_all async

extract_all(model, *, scope, timeout=0, limit=None)

Extract multiple items from repeated containers on the page.

Each element matching the scope selector generates one model instance. Fields are resolved relative to each scope container.

PARAMETER DESCRIPTION
model

ExtractionModel subclass defining the extraction schema.

TYPE: type[T]

scope

CSS/XPath selector for the repeated container (required).

TYPE: str

timeout

Seconds to wait for elements (0 = no wait).

TYPE: int DEFAULT: 0

limit

Maximum number of items to extract (None = all).

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
list[T]

List of populated model instances.

current_url async

current_url()

Get current page URL (reflects redirects and client-side navigation).

page_source async

page_source()

Get complete HTML source of current page (live DOM state).

title async

title()

Get current page title.

enable_page_events async

enable_page_events()

Enable CDP Page domain events (load, navigation, dialogs, etc.).

enable_network_events async

enable_network_events()

Enable CDP Network domain events (requests, responses, etc.).

enable_fetch_events async

enable_fetch_events(handle_auth=False, resource_type=None, request_stage=None)

Enable CDP Fetch domain for request interception.

PARAMETER DESCRIPTION
handle_auth

Intercept authentication challenges.

TYPE: bool DEFAULT: False

resource_type

Filter by resource type (all if None).

TYPE: ResourceType | None DEFAULT: None

request_stage

When to intercept (Request/Response).

TYPE: RequestStage | None DEFAULT: None

Note

Intercepted requests must be explicitly continued or timeout.

enable_dom_events async

enable_dom_events()

Enable CDP DOM domain events (document structure changes).

enable_runtime_events async

enable_runtime_events()

Enable CDP Runtime domain events.

enable_intercept_file_chooser_dialog async

enable_intercept_file_chooser_dialog()

Enable file chooser dialog interception for automated uploads.

Note

Use expect_file_chooser context manager for convenience.

disable_fetch_events async

disable_fetch_events()

Disable CDP Fetch domain and release paused requests.

disable_page_events async

disable_page_events()

Disable CDP Page domain events.

disable_network_events async

disable_network_events()

Disable CDP Network domain events.

disable_dom_events async

disable_dom_events()

Disable CDP DOM domain events.

disable_runtime_events async

disable_runtime_events()

Disable CDP Runtime domain events.

disable_intercept_file_chooser_dialog async

disable_intercept_file_chooser_dialog()

Disable file chooser dialog interception.

close async

close()

Close this browser tab.

Note

Tab instance becomes invalid after calling this method.

find_shadow_roots async

find_shadow_roots(deep=False, timeout=0)

Find all shadow roots in the page.

Traverses the entire DOM tree (including iframes and nested shadow DOMs) to collect all shadow roots found. This is especially useful when the shadow host element selector is unknown or dynamic (e.g., Cloudflare challenge pages).

PARAMETER DESCRIPTION
deep

If True, also traverses cross-origin iframes (OOPIFs) to discover shadow roots inside them. The returned ShadowRoot objects will automatically route CDP commands through the correct OOPIF session.

TYPE: bool DEFAULT: False

timeout

Maximum seconds to wait for shadow roots to appear. When > 0, repeatedly polls the DOM (starting every 20 ms and backing off to 250 ms) until at least one shadow root is found or the timeout expires. Useful when shadow hosts are injected asynchronously (e.g., Cloudflare Turnstile loading inside an OOPIF).

TYPE: float DEFAULT: 0

RETURNS DESCRIPTION
list[ShadowRoot]

List of ShadowRoot instances found in the page.

RAISES DESCRIPTION
WaitElementTimeout

If timeout > 0 and no shadow roots are found within the specified duration.

bring_to_front async

bring_to_front()

Brings the page to front.

get_cookies async

get_cookies()

Get all cookies of this tab's browser context.

A tab that lives in a browser context created with browser.create_browser_context() reads them through the browser connection, because Chrome only accepts browserContextId on the browser target, not on a page session.

get_network_response_body async

get_network_response_body(request_id)

Get the response body for a given request ID.

PARAMETER DESCRIPTION
request_id

Request ID to get the response body for.

TYPE: str

RETURNS DESCRIPTION
str

The response body for the given request ID.

RAISES DESCRIPTION
NetworkEventsNotEnabled

If network events are not enabled.

get_network_logs async

get_network_logs(filter=None)

Get network logs.

PARAMETER DESCRIPTION
filter

Filter to apply to the network logs.

TYPE: str | None DEFAULT: None

RETURNS DESCRIPTION
list[RequestWillBeSentEvent]

The network logs.

RAISES DESCRIPTION
NetworkEventsNotEnabled

If network events are not enabled.

set_cookies async

set_cookies(cookies)

Set multiple cookies for current page.

PARAMETER DESCRIPTION
cookies

Cookie parameters (name/value required, others optional).

TYPE: list[CookieParam]

Note

Defaults to current page's domain if not specified.

delete_all_cookies async

delete_all_cookies()

Delete all cookies from current browser context.

apply_fingerprint async

apply_fingerprint(fingerprint, *, cross_origin_iframes=True)

Apply a browser fingerprint profile to this tab.

Delegates to a per-tab :class:FingerprintApplier (created once and reused), which overrides browser identity signals via CDP commands and JavaScript injection and replays them on Web Worker targets and cross-site iframes. Call before navigating to any page for full effect, since JS overrides register via Page.addScriptToEvaluateOnNewDocument.

PARAMETER DESCRIPTION
fingerprint

Fingerprint configuration. Only specified fields are overridden; unspecified fields keep real browser values.

TYPE: FingerprintConfig

cross_origin_iframes

When true (default), the identity is also replayed into every cross-site iframe (OOPIF), so a fingerprinting script embedded in a cross-origin challenge or captcha frame reads the same identity as the page. Set false to cover only the top page, same-origin frames, and workers.

TYPE: bool DEFAULT: True

go_to async

go_to(url, timeout=300)

Navigate to URL and wait for loading to complete.

PARAMETER DESCRIPTION
url

Target URL to navigate to.

TYPE: str

timeout

Maximum seconds to wait for page load (default 300).

TYPE: int DEFAULT: 300

RAISES DESCRIPTION
NavigationError

If the navigation fails (e.g., DNS error).

PageLoadTimeout

If page doesn't finish loading within timeout.

wait_for_url async

wait_for_url(url, timeout=30)

Wait until the tab's URL matches a pattern and return it.

Covers full navigations and in-page changes (pushState) alike, because it reads the live URL instead of listening to one event.

PARAMETER DESCRIPTION
url

A glob ('*/checkout/*'), a compiled regular expression, or a callable that receives the URL and returns True to match.

TYPE: UrlPattern

timeout

Maximum seconds to wait.

TYPE: float DEFAULT: 30

RETURNS DESCRIPTION
str

The URL that matched.

RAISES DESCRIPTION
WaitTimeout

If no matching URL is seen within timeout.

wait_for_script async

wait_for_script(script, timeout=30)

Wait until a JavaScript expression evaluates to a truthy value and return it.

Truthiness is JavaScript's, judged on the page side: a DOM node, a function, an object (even {} or []) and a non-empty string or non-zero number are truthy; undefined, null, false, 0, NaN, -0, 0n and '' are falsy. A promise is awaited and its settled value is judged.

PARAMETER DESCRIPTION
script

An expression such as 'window.app && window.app.ready', or a script with a return.

TYPE: str

timeout

Maximum seconds to wait.

TYPE: float DEFAULT: 30

RETURNS DESCRIPTION
Any

The value itself when it is a primitive (string, number, True),

Any

True for any object, node or function.

RAISES DESCRIPTION
WaitTimeout

If the script stays falsy for timeout seconds.

ScriptEvaluationError

As soon as the script throws or its promise rejects, with the JavaScript error text.

wait_for_absence async

wait_for_absence(id=None, class_name=None, name=None, tag_name=None, text=None, timeout=30, **attributes)

Wait until no element matches the criteria, the same criteria find() takes.

Use it for the thing that has to go away before you continue: a loading overlay, a "saving" badge, a modal that closes on its own.

PARAMETER DESCRIPTION
id, class_name, name, tag_name, text, **attributes

Criteria, as in find().

timeout

Maximum seconds to wait.

TYPE: float DEFAULT: 30

RAISES DESCRIPTION
WaitTimeout

If a matching element is still present after timeout.

wait_for_network_idle async

wait_for_network_idle(idle_time=0.5, timeout=30)

Wait until the page has had no network requests in flight for idle_time seconds.

Requests are counted from the moment this method is called, so call it right after the action that starts them (a navigation, a click that loads data). A request that never finishes keeps the page busy until timeout.

PARAMETER DESCRIPTION
idle_time

Seconds without any request in flight that count as idle.

TYPE: float DEFAULT: 0.5

timeout

Maximum seconds to wait.

TYPE: float DEFAULT: 30

RAISES DESCRIPTION
WaitTimeout

If the network is never idle for idle_time within timeout.

expect_navigation async

expect_navigation(url=None, timeout=30)

Wait for a navigation started inside the block, and for the new page to load.

Register before acting, act inside the block, and the block only exits once the main frame has navigated (to a URL matching url, when given) and reached the load state set in options.page_load_state.

PARAMETER DESCRIPTION
url

Optional glob, regular expression or callable the new URL must match.

TYPE: UrlPattern | None DEFAULT: None

timeout

Maximum seconds to wait after the block.

TYPE: float DEFAULT: 30

RAISES DESCRIPTION
WaitTimeout

If the navigation or the load does not happen in time.

expect_request async

expect_request(url, timeout=30)

Capture the first request whose URL matches, sent during the block.

The handle is empty inside the block and filled when the block exits, which is when the wait happens.

PARAMETER DESCRIPTION
url

A glob, a compiled regular expression, or a callable on the URL.

TYPE: UrlPattern

timeout

Maximum seconds to wait after the block for the request.

TYPE: float DEFAULT: 30

YIELDS DESCRIPTION
RequestHandle

URL, method, headers and body of the request.

TYPE:: AsyncGenerator[RequestHandle, None]

RAISES DESCRIPTION
WaitTimeout

If no matching request is sent within timeout.

expect_response async

expect_response(url, timeout=30)

Capture the first response whose URL matches, received during the block.

The block exits once the response has arrived and its body has been read, so response.json() is ready right after the block: the usual way to read the API call a click triggers instead of scraping the DOM. A 204, 205 or 304 response has no body by definition (Chrome reports its load as aborted), so it completes with an empty body.

PARAMETER DESCRIPTION
url

A glob, a compiled regular expression, or a callable on the URL.

TYPE: UrlPattern

timeout

Maximum seconds to wait after the block for the response.

TYPE: float DEFAULT: 30

YIELDS DESCRIPTION
ResponseHandle

status, headers and body of the response.

TYPE:: AsyncGenerator[ResponseHandle, None]

RAISES DESCRIPTION
WaitTimeout

If no matching response completes within timeout.

refresh async

refresh(ignore_cache=False, script_to_evaluate_on_load=None)

Reload current page and wait for completion.

PARAMETER DESCRIPTION
ignore_cache

Bypass browser cache if True.

TYPE: bool DEFAULT: False

script_to_evaluate_on_load

JavaScript to execute after load.

TYPE: str | None DEFAULT: None

RAISES DESCRIPTION
PageLoadTimeout

If page doesn't finish loading within timeout.

take_screenshot async

take_screenshot(path=None, quality=100, beyond_viewport=False, as_base64=False)

Capture screenshot of current page.

PARAMETER DESCRIPTION
path

File path for screenshot (extension determines format).

TYPE: str | Path | None DEFAULT: None

quality

Image quality 0-100 (default 100).

TYPE: int DEFAULT: 100

beyond_viewport

The page will be scrolled to the bottom and the screenshot will include the entire page

TYPE: bool DEFAULT: False

as_base64

Return as base64 string instead of saving file.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
str | None

Base64 screenshot data if as_base64=True, None otherwise.

RAISES DESCRIPTION
InvalidFileExtension

If file extension not supported.

MissingScreenshotPath

If path is None and as_base64 is False.

print_to_pdf async

print_to_pdf(path=None, landscape=False, display_header_footer=False, print_background=True, scale=1.0, as_base64=False)

Generate PDF of current page.

PARAMETER DESCRIPTION
path

File path for PDF output. Required if as_base64=False.

TYPE: str | Path | None DEFAULT: None

landscape

Use landscape orientation.

TYPE: bool DEFAULT: False

display_header_footer

Include header/footer.

TYPE: bool DEFAULT: False

print_background

Include background graphics.

TYPE: bool DEFAULT: True

scale

Scale factor (0.1-2.0).

TYPE: float DEFAULT: 1.0

as_base64

Return as base64 string instead of saving.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
str | None

Base64 PDF data if as_base64=True, None otherwise.

RAISES DESCRIPTION
ValueError

If path is not provided when as_base64=False.

save_bundle async

save_bundle(path, inline_assets=False)

Save current page and its assets as a .zip bundle for offline viewing.

Captures the page HTML along with CSS, JS, images, fonts, and media into a single zip archive. The archive contains an index.html with URLs rewritten to reference local asset files.

PARAMETER DESCRIPTION
path

Destination path for the .zip file.

TYPE: str | Path

inline_assets

When True, embed all assets directly into index.html using data URIs, <style>, and <script> tags instead of saving them as separate files.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
InvalidFileExtension

If path does not end with .zip.

has_dialog async

has_dialog()

Check if JavaScript dialog is currently displayed.

Note

Page events must be enabled to detect dialogs.

get_dialog_message async

get_dialog_message()

Get message text from current JavaScript dialog.

RAISES DESCRIPTION
NoDialogPresent

If no dialog is currently displayed.

handle_dialog async

handle_dialog(accept, prompt_text=None)

Respond to JavaScript dialog.

PARAMETER DESCRIPTION
accept

Accept/confirm dialog if True, dismiss/cancel if False.

TYPE: bool

prompt_text

Text for prompt dialogs (ignored for alert/confirm).

TYPE: str | None DEFAULT: None

RAISES DESCRIPTION
NoDialogPresent

If no dialog is currently displayed.

Note

Page events must be enabled to handle dialogs.

execute_script async

execute_script(script, *, object_group=None, include_command_line_api=None, silent=None, context_id=None, return_by_value=None, generate_preview=None, user_gesture=None, await_promise=None, throw_on_side_effect=None, timeout=None, disable_breaks=None, repl_mode=None, allow_unsafe_eval_blocked_by_csp=None, unique_context_id=None, serialization_options=None)

Execute JavaScript in page context.

PARAMETER DESCRIPTION
script

JavaScript code to execute.

TYPE: str

object_group

Symbolic group name for the result (Runtime.evaluate).

TYPE: str | None DEFAULT: None

include_command_line_api

Whether to include command line API (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

silent

Whether to silence exceptions (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

context_id

ID of the execution context to evaluate in (Runtime.evaluate).

TYPE: int | None DEFAULT: None

return_by_value

Whether to return the result by value instead of reference (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

generate_preview

Whether to generate a preview for the result (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

user_gesture

Whether to treat evaluation as initiated by user gesture (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

await_promise

Whether to await promise result (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

throw_on_side_effect

Whether to throw if side effect cannot be ruled out (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

timeout

Timeout in milliseconds (Runtime.evaluate).

TYPE: float | None DEFAULT: None

disable_breaks

Whether to disable breakpoints during evaluation (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

repl_mode

Whether to execute in REPL mode (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

allow_unsafe_eval_blocked_by_csp

Allow unsafe evaluation (Runtime.evaluate).

TYPE: bool | None DEFAULT: None

unique_context_id

Unique context ID for evaluation (Runtime.evaluate).

TYPE: str | None DEFAULT: None

serialization_options

Serialization options for the result (Runtime.evaluate).

TYPE: SerializationOptions | None DEFAULT: None

RETURNS DESCRIPTION
EvaluateResponse

The result of the script execution.

TYPE: EvaluateResponse

RAISES DESCRIPTION
InvalidScriptWithElement

If the script references argument; run it through WebElement.execute_script() instead.

Examples:

Execute a simple script to log a message

await tab.execute_script('console.log("Hello World")')

Execute a script that returns the page title

await tab.execute_script('return document.title')

continue_request async

continue_request(request_id, url=None, method=None, post_data=None, headers=None, intercept_response=None)

Continue paused request without modifications.

fail_request async

fail_request(request_id, error_reason)

Fail request with error code.

fulfill_request async

fulfill_request(request_id, response_code, response_headers=None, body=None, response_phrase=None)

Fulfill request with response data.

continue_with_auth async

continue_with_auth(request_id, auth_challenge_response, proxy_username=None, proxy_password=None)

Continue a paused request replying to an authentication challenge.

Useful for proxy auth (407) or server auth (401) when Fetch is enabled with handle_auth=True.

expect_file_chooser async

expect_file_chooser(files)

Context manager for automatic file upload handling.

PARAMETER DESCRIPTION
files

File path(s) for upload.

TYPE: str | Path | list[str | Path]

expect_cloudflare_turnstile async

expect_cloudflare_turnstile(time_to_wait_captcha=5)

Handle the Cloudflare Turnstile widget if it appears while the block runs.

PARAMETER DESCRIPTION
time_to_wait_captcha

Timeout for captcha detection (default 5s).

TYPE: float DEFAULT: 5

expect_download async

expect_download(keep_file_at=None, timeout=None)

Context manager for handling a file download triggered inside the block.

Behavior: - If keep_file_at is provided, configure browser to save into that directory and keep file. - Otherwise, a temporary directory is used and cleaned up after the context.

PARAMETER DESCRIPTION
keep_file_at

Directory to persist the file. If None, uses a temporary directory and cleans it up afterwards.

TYPE: str | Path | None DEFAULT: None

timeout

Max seconds to wait for download completion. Defaults to 60.

TYPE: float | None DEFAULT: None

YIELDS DESCRIPTION
DownloadHandle

Handle to read the downloaded file (bytes/base64) and check its path.

TYPE:: AsyncGenerator[DownloadHandle, None]

on async

on(event_name: str, callback: Callable[[dict], Any], temporary: bool = False) -> int
on(event_name: str, callback: Callable[[dict], Awaitable[Any]], temporary: bool = False) -> int
on(event_name, callback, temporary=False)

Register CDP event listener.

Callback runs in background task to prevent blocking.

PARAMETER DESCRIPTION
event_name

CDP event name (e.g., 'Page.loadEventFired').

callback

Function called on event (sync or async).

temporary

Remove after first invocation.

DEFAULT: False

RETURNS DESCRIPTION
int

Callback ID for removal.

Note

Corresponding domain must be enabled before events fire.

remove_callback async

remove_callback(callback_id)

Remove callback from tab.

clear_callbacks async

clear_callbacks()

Clear all registered event callbacks.

find async

find(id: str | None = ..., class_name: str | None = ..., name: str | None = ..., tag_name: str | None = ..., text: str | None = ..., timeout: int = ..., find_all: Literal[False] = False, raise_exc: Literal[True] = True, **attributes) -> WebElement
find(id: str | None = ..., class_name: str | None = ..., name: str | None = ..., tag_name: str | None = ..., text: str | None = ..., timeout: int = ..., find_all: Literal[False] = False, raise_exc: Literal[False] = False, **attributes) -> WebElement | None
find(id: str | None = ..., class_name: str | None = ..., name: str | None = ..., tag_name: str | None = ..., text: str | None = ..., timeout: int = ..., find_all: Literal[True] = True, raise_exc: Literal[True] = True, **attributes) -> list[WebElement]
find(id: str | None = ..., class_name: str | None = ..., name: str | None = ..., tag_name: str | None = ..., text: str | None = ..., timeout: int = ..., find_all: Literal[True] = True, raise_exc: Literal[False] = False, **attributes) -> list[WebElement] | None
find(id: str | None = ..., class_name: str | None = ..., name: str | None = ..., tag_name: str | None = ..., text: str | None = ..., timeout: int = ..., find_all: bool = ..., raise_exc: bool = ..., **attributes) -> WebElement | list[WebElement] | None
find(id=None, class_name=None, name=None, tag_name=None, text=None, timeout=0, find_all=False, raise_exc=True, **attributes)

Find element(s) using combination of common HTML attributes.

Flexible element location using standard attributes. Multiple attributes can be combined for specific selectors (builds XPath when multiple specified).

PARAMETER DESCRIPTION
id

Element ID attribute value.

TYPE: str | None DEFAULT: None

class_name

CSS class name to match.

TYPE: str | None DEFAULT: None

name

Element name attribute value.

TYPE: str | None DEFAULT: None

tag_name

HTML tag name (e.g., "div", "input").

TYPE: str | None DEFAULT: None

text

Text content to match within element.

TYPE: str | None DEFAULT: None

timeout

Maximum seconds to wait for elements to appear.

TYPE: int DEFAULT: 0

find_all

If True, returns all matches; if False, first match only.

TYPE: bool DEFAULT: False

raise_exc

Whether to raise exception if no elements found.

TYPE: bool DEFAULT: True

**attributes

Additional HTML attributes to match.

TYPE: dict[str, str] DEFAULT: {}

RETURNS DESCRIPTION
WebElement | list[WebElement] | None

WebElement, list[WebElement], or None based on find_all and raise_exc.

RAISES DESCRIPTION
ValueError

If no search criteria provided.

ElementNotFound

If no elements found and raise_exc=True.

WaitElementTimeout

If timeout specified and no elements appear in time.

NotImplementedError

If called on a ShadowRoot (use query() with CSS instead).

query async

query(expression: str, timeout: int = ..., find_all: Literal[False] = False, raise_exc: Literal[True] = True) -> WebElement
query(expression: str, timeout: int = ..., find_all: Literal[False] = False, raise_exc: Literal[False] = False) -> WebElement | None
query(expression: str, timeout: int = ..., find_all: Literal[True] = True, raise_exc: Literal[True] = True) -> list[WebElement]
query(expression: str, timeout: int = ..., find_all: Literal[True] = True, raise_exc: Literal[False] = False) -> list[WebElement] | None
query(expression: str, timeout: int = ..., find_all: bool = ..., raise_exc: bool = ...) -> WebElement | list[WebElement] | None
query(expression, timeout=0, find_all=False, raise_exc=True)

Find element(s) using raw CSS selector or XPath expression.

Direct access using CSS or XPath syntax. Selector type automatically determined based on expression pattern.

PARAMETER DESCRIPTION
expression

Selector expression (CSS, XPath, ID with #, class with .).

TYPE: str

timeout

Maximum seconds to wait for elements to appear.

TYPE: int DEFAULT: 0

find_all

If True, returns all matches; if False, first match only.

TYPE: bool DEFAULT: False

raise_exc

Whether to raise exception if no elements found.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
WebElement | list[WebElement] | None

WebElement, list[WebElement], or None based on find_all and raise_exc.

RAISES DESCRIPTION
ElementNotFound

If no elements found and raise_exc=True.

WaitElementTimeout

If timeout specified and no elements appear in time.

NotImplementedError

If called with XPath on a ShadowRoot.

query_script async

query_script(function_declaration, arguments=None, execution_context_id=None)

Run a JavaScript function that returns elements and wrap them as WebElements.

The function runs with the search root bound to this (document on a Tab, the frame document on an iframe element, the element itself on a WebElement, the root on a ShadowRoot) in the same execution context and iframe routing that query() uses. It may return a single Element, a NodeList, an array of Elements, or null.

PARAMETER DESCRIPTION
function_declaration

JavaScript function source, e.g. function(tag) { return this.querySelectorAll(tag); }.

TYPE: str

arguments

CDP call arguments passed positionally to the function.

TYPE: list[CallArgument] | None DEFAULT: None

execution_context_id

Run in this execution context of the frame (for example an isolated world created with Page.createIsolatedWorld) with this bound to that context's document. Ignored when the root is a non-iframe element, whose object id already fixes the context.

TYPE: int | None DEFAULT: None

RETURNS DESCRIPTION
list[WebElement]

WebElements for every element the function returned, in return order.

RAISES DESCRIPTION
ScriptException

If the function throws or fails to compile.

CommandFailed

If the browser rejects the command itself.

execute_command async

execute_command(command, timeout=60)

Send a raw CDP command through this object's session.

The command is routed exactly like the object's own operations: a Tab sends it to the page session, a WebElement inside an out-of-process iframe sends it to that frame's session. Build commands with the factories in pydoll.commands or pass a plain {'method': ..., 'params': ...} dict for methods pydoll does not wrap.

PARAMETER DESCRIPTION
command

CDP command to send.

TYPE: Command[T_CommandParams, T_CommandResponse]

timeout

Seconds to wait for the browser's answer.

TYPE: int DEFAULT: 60

RETURNS DESCRIPTION
T_CommandResponse

The browser's response, with the domain result under 'result'.

RAISES DESCRIPTION
CommandFailed

If the browser answers with an error.

CommandExecutionTimeout

If no answer arrives within timeout.