Skip to content

WebElement

Representa um elemento localizado: clicar, digitar, ler texto e atributos, tirar screenshot e percorrer o DOM. Saiba mais em Pesquisa de elementos.

pydoll.elements.web_element.WebElement

WebElement(object_id, connection_handler, method=None, selector=None, attributes_list=None, mouse=None)

Bases: FindElementsMixin

DOM element wrapper for browser automation.

Provides comprehensive functionality for element interaction, inspection, and manipulation using Chrome DevTools Protocol commands.

Initialize WebElement wrapper.

PARAMETER DESCRIPTION
object_id

Unique CDP object identifier for this DOM element.

TYPE: str

connection_handler

Connection instance for browser communication.

TYPE: ConnectionHandler

method

Search method used to find this element (for debugging).

TYPE: str | None DEFAULT: None

selector

Selector string used to find this element (for debugging).

TYPE: str | None DEFAULT: None

attributes_list

Flat list of alternating attribute names and values.

TYPE: list[str] | None DEFAULT: None

mouse

Optional Mouse instance for humanized click behavior.

TYPE: Mouse | None DEFAULT: None

Note

Mouse and Keyboard follow different ownership strategies. The tab's Mouse is shared with the elements of its document and of its same-process iframes, so the cursor keeps one position across interactions; an element inside an out-of-process iframe uses a mouse bound to that frame's session, cached on the iframe context (see _input_mouse). Keyboard is created per element and routes commands through the element's own _execute_command.

attributes property

attributes

Read-only copy of the element's cached attributes.

value property

value

Element's value attribute (for form elements).

class_name property

class_name

Element's CSS class name(s).

id property

id

Element's ID attribute.

tag_name property

tag_name

Element's HTML tag name.

is_iframe property

is_iframe

Whether the element represents an iframe.

is_enabled property

is_enabled

Whether element is enabled (not disabled).

text async

text()

Visible text content of the element.

bounds async

bounds()

Element's bounding box coordinates.

Returns coordinates in CSS pixels relative to document origin.

inner_html async

inner_html()

iframe_context async

iframe_context()

Return the resolved iframe context for this element when it is an <iframe>.

The context includes: frame_id, document_url, execution_context_id, document_object_id and, for OOPIF targets, the session_id and session_handler used for routing commands. A context resolved earlier is reused while it still describes the frame's current document, so the elements already found inside the frame keep a live session; after a navigation or reload it is resolved afresh and the old one is closed. Non-iframe elements return None.

RETURNS DESCRIPTION
IFrameContext | None

IFrameContext | None: Resolved iframe context or None for non-iframes.

get_attribute

get_attribute(name)

Get element attribute value.

Note

Only provides attributes available when element was located. For dynamic attributes, consider using JavaScript execution.

get_bounds_using_js async

get_bounds_using_js()

Get element bounds using JavaScript getBoundingClientRect().

Returns coordinates relative to viewport (alternative to bounds property).

get_parent_element async

get_parent_element()

Element's parent element.

get_shadow_root async

get_shadow_root(timeout=0)

Get the shadow root attached to this element.

PARAMETER DESCRIPTION
timeout

Maximum seconds to wait for the shadow root to appear. When > 0, repeatedly polls (starting every 20 ms and backing off to 250 ms) until a shadow root is found or the timeout expires.

TYPE: float DEFAULT: 0

RETURNS DESCRIPTION
ShadowRoot

ShadowRoot instance for traversing the shadow DOM.

RAISES DESCRIPTION
ShadowRootNotFound

If no shadow root is attached (when timeout=0).

WaitElementTimeout

If timeout > 0 and no shadow root appears within the specified duration.

get_children_elements async

get_children_elements(max_depth=1, tag_filter=[], raise_exc=False)

Retrieve all direct and nested child elements of this element.

PARAMETER DESCRIPTION
max_depth

Maximum depth to traverse when finding children. Defaults to 1 for direct children only.

TYPE: int DEFAULT: 1

tag_filter

List of HTML tag names to filter results. If empty, returns all child elements regardless of tag. Defaults to [].

TYPE: list[str] DEFAULT: []

RETURNS DESCRIPTION
list[WebElement]

list[WebElement]: List of child WebElement objects found within the specified depth and matching the tag filter criteria.

RAISES DESCRIPTION
ElementNotFound

If no child elements are found for this element and raise_exc is True.

get_siblings_elements async

get_siblings_elements(tag_filter=[], raise_exc=False)

Retrieve all sibling elements of this element (elements at the same DOM level).

PARAMETER DESCRIPTION
tag_filter

List of HTML tag names to filter results. If empty, returns all sibling elements regardless of tag. Defaults to [].

TYPE: list[str] DEFAULT: []

RETURNS DESCRIPTION
list[WebElement]

list[WebElement]: List of sibling WebElement objects that share the same parent as this element and match the tag filter criteria.

RAISES DESCRIPTION
ElementNotFound

If no sibling elements are found for this element

take_screenshot async

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

Capture screenshot of this element only.

Automatically scrolls element into view before capturing.

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

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.

scroll_into_view async

scroll_into_view()

Scroll element into the viewport, keeping a margin from every edge.

DOM.scrollIntoViewIfNeeded aligns a partially visible element with the closest viewport edge. That leaves it under the overlay scrollbar the scroll itself reveals on macOS, so the mouse events that follow land on the scrollbar instead of the element. Asking for the element's box plus a margin keeps it clear of the edges. When the box cannot be read the plain behaviour is kept.

wait_until async

wait_until(*, is_visible=False, is_interactable=False, is_hidden=False, is_detached=False, is_enabled=False, timeout=0)

Wait for the element to meet every condition you set to True.

is_visible and is_interactable wait for the element to show up and accept input; is_hidden waits for it to leave the screen (a spinner finishing), is_detached for it to leave the DOM, and is_enabled for its disabled attribute to be cleared. With the default timeout of 0 the conditions are checked once.

RAISES DESCRIPTION
ValueError

If no condition is set to True.

WaitElementTimeout

If the conditions are not all met within timeout.

click_using_js async

click_using_js()

Click element using JavaScript click() method.

RAISES DESCRIPTION
ElementNotVisible

If element is not visible.

ElementNotInteractable

If element couldn't be clicked.

Note

For

click async

click(x_offset=0, y_offset=0, hold_time=0, humanize=False)

Click element using simulated mouse events.

PARAMETER DESCRIPTION
x_offset

Horizontal offset from element center.

TYPE: int DEFAULT: 0

y_offset

Vertical offset from element center.

TYPE: int DEFAULT: 0

hold_time

Seconds to keep the button down between press and release (used when humanize=False). Zero by default, so a plain click is two back-to-back events; pass humanize=True for human timing.

TYPE: float DEFAULT: 0

humanize

When True and a Mouse instance is available, uses humanized Bezier curve movement from the current tracked position to the element center before clicking. When False, dispatches raw CDP mousePressed/mouseReleased events directly.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ElementNotVisible

If element is not visible.

Note

For

hover async

hover(x_offset=0, y_offset=0, humanize=False)

Move the mouse over the element without clicking.

Scrolls the element into view and moves the pointer to its center plus the offsets, so hover styles, tooltips and menus that open on mouseover react as they would for a person.

PARAMETER DESCRIPTION
x_offset

Horizontal offset from the element center.

TYPE: int DEFAULT: 0

y_offset

Vertical offset from the element center.

TYPE: int DEFAULT: 0

humanize

Move along a curved path with human timing instead of jumping straight to the point.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ElementNotVisible

If the element is not visible.

double_click async

double_click(x_offset=0, y_offset=0, humanize=False)

Double-click the element.

Sends the two press-and-release pairs a real double click produces, with the second pair carrying clickCount=2, so the page receives dblclick as well as the two click events.

PARAMETER DESCRIPTION
x_offset

Horizontal offset from the element center.

TYPE: int DEFAULT: 0

y_offset

Vertical offset from the element center.

TYPE: int DEFAULT: 0

humanize

Move the mouse along a curved path before clicking.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ElementNotVisible

If the element is not visible.

focus async

focus()

Focus this element via CDP DOM.focus command.

clear async

clear()

Clear the current value of the element.

Supports standard inputs, textareas, and contenteditable elements. Dispatches input and change events so frameworks detect the update.

RAISES DESCRIPTION
ElementNotInteractable

If the element does not accept text input.

insert_text async

insert_text(text)

Insert text into element using JavaScript.

Supports standard inputs, textareas, contenteditable elements, and rich text editors. Inserts text at cursor position or replaces selected text.

PARAMETER DESCRIPTION
text

Text to insert.

TYPE: str

RAISES DESCRIPTION
ElementNotInteractable

If element does not accept text input.

Note

Uses JavaScript for maximum compatibility with all input types. Automatically handles input/textarea and contenteditable elements.

set_input_files async

set_input_files(files)

Set file paths for file input element.

PARAMETER DESCRIPTION
files

list of absolute file paths to existing files.

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

RAISES DESCRIPTION
ElementNotAFileInput

If element is not a file input.

type_text async

type_text(text, humanize=False)

Type text character by character.

PARAMETER DESCRIPTION
text

Text to type into the element.

TYPE: str

humanize

When True, simulates human-like typing.

TYPE: bool DEFAULT: False

is_editable async

is_editable()

Check if element can accept text input.

RETURNS DESCRIPTION
bool

True if element is editable (input, textarea, or contenteditable).

is_visible async

is_visible()

Check if element is visible using comprehensive JavaScript visibility test.

is_detached async

is_detached()

Whether the element is no longer part of a document (removed or replaced).

is_on_top async

is_on_top()

Check if element is topmost at its center point (not covered by overlays).

is_interactable async

is_interactable()

Check if element is interactable based on visibility and position.

execute_script async

execute_script(script, *, arguments=None, silent=None, return_by_value=None, generate_preview=None, user_gesture=None, await_promise=None, execution_context_id=None, object_group=None, throw_on_side_effect=None, unique_context_id=None, serialization_options=None)

Execute JavaScript in element context.

PARAMETER DESCRIPTION
script

JavaScript code to execute. Use 'this' to reference this element.

TYPE: str

arguments

Arguments to pass to the function (Runtime.callFunctionOn).

TYPE: list[CallArgument] | None DEFAULT: None

silent

Whether to silence exceptions (Runtime.callFunctionOn).

TYPE: bool | None DEFAULT: None

return_by_value

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

TYPE: bool | None DEFAULT: None

generate_preview

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

TYPE: bool | None DEFAULT: None

user_gesture

Whether to treat the call as initiated by user gesture (Runtime.callFunctionOn).

TYPE: bool | None DEFAULT: None

await_promise

Whether to await promise result (Runtime.callFunctionOn).

TYPE: bool | None DEFAULT: None

execution_context_id

ID of the execution context to call the function in (Runtime.callFunctionOn).

TYPE: int | None DEFAULT: None

object_group

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

TYPE: str | None DEFAULT: None

throw_on_side_effect

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

TYPE: bool | None DEFAULT: None

unique_context_id

Unique context ID for the function call (Runtime.callFunctionOn).

TYPE: str | None DEFAULT: None

serialization_options

Serialization options for the result (Runtime.callFunctionOn).

TYPE: SerializationOptions | None DEFAULT: None

RETURNS DESCRIPTION
CallFunctionOnResponse

The result of the script execution.

TYPE: CallFunctionOnResponse

Examples:

Click the element

await element.execute_script('this.click()')

Modify element style

await element.execute_script('this.style.border = "2px solid red"')

Get element text

result = await element.execute_script('return this.textContent', return_by_value=True)

Set element content

await element.execute_script('this.textContent = "Hello World"')

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.