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:
|
connection_handler
|
Connection instance for browser communication.
TYPE:
|
method
|
Search method used to find this element (for debugging).
TYPE:
|
selector
|
Selector string used to find this element (for debugging).
TYPE:
|
attributes_list
|
Flat list of alternating attribute names and values.
TYPE:
|
mouse
|
Optional Mouse instance for humanized click behavior.
TYPE:
|
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.
bounds
async
Element's bounding box coordinates.
Returns coordinates in CSS pixels relative to document origin.
iframe_context
async
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 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 element bounds using JavaScript getBoundingClientRect().
Returns coordinates relative to viewport (alternative to bounds property).
get_shadow_root
async
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:
|
| 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
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:
|
tag_filter
|
List of HTML tag names to filter results. If empty, returns all child elements regardless of tag. Defaults to [].
TYPE:
|
| 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
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:
|
| 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
Capture screenshot of this element only.
Automatically scrolls element into view before capturing.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File path for screenshot (extension determines format).
TYPE:
|
quality
|
Image quality 0-100 (default 100).
TYPE:
|
as_base64
|
Return as base64 string instead of saving file.
TYPE:
|
| 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 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 |
click_using_js
async
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 element using simulated mouse events.
| PARAMETER | DESCRIPTION |
|---|---|
x_offset
|
Horizontal offset from element center.
TYPE:
|
y_offset
|
Vertical offset from element center.
TYPE:
|
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:
|
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:
|
| RAISES | DESCRIPTION |
|---|---|
ElementNotVisible
|
If element is not visible. |
Note
For
hover
async
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:
|
y_offset
|
Vertical offset from the element center.
TYPE:
|
humanize
|
Move along a curved path with human timing instead of jumping straight to the point.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ElementNotVisible
|
If the element is not visible. |
double_click
async
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:
|
y_offset
|
Vertical offset from the element center.
TYPE:
|
humanize
|
Move the mouse along a curved path before clicking.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ElementNotVisible
|
If the element is not visible. |
clear
async
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 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:
|
| 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 file paths for file input element.
| PARAMETER | DESCRIPTION |
|---|---|
files
|
list of absolute file paths to existing files.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ElementNotAFileInput
|
If element is not a file input. |
type_text
async
Type text character by character.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
Text to type into the element.
TYPE:
|
humanize
|
When True, simulates human-like typing.
TYPE:
|
is_editable
async
Check if element can accept text input.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if element is editable (input, textarea, or contenteditable). |
is_visible
async
Check if element is visible using comprehensive JavaScript visibility test.
is_detached
async
Whether the element is no longer part of a document (removed or replaced).
is_on_top
async
Check if element is topmost at its center point (not covered by overlays).
is_interactable
async
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:
|
arguments
|
Arguments to pass to the function (Runtime.callFunctionOn).
TYPE:
|
silent
|
Whether to silence exceptions (Runtime.callFunctionOn).
TYPE:
|
return_by_value
|
Whether to return the result by value instead of reference (Runtime.callFunctionOn).
TYPE:
|
generate_preview
|
Whether to generate a preview for the result (Runtime.callFunctionOn).
TYPE:
|
user_gesture
|
Whether to treat the call as initiated by user gesture (Runtime.callFunctionOn).
TYPE:
|
await_promise
|
Whether to await promise result (Runtime.callFunctionOn).
TYPE:
|
execution_context_id
|
ID of the execution context to call the function in (Runtime.callFunctionOn).
TYPE:
|
object_group
|
Symbolic group name for the result (Runtime.callFunctionOn).
TYPE:
|
throw_on_side_effect
|
Whether to throw if side effect cannot be ruled out (Runtime.callFunctionOn).
TYPE:
|
unique_context_id
|
Unique context ID for the function call (Runtime.callFunctionOn).
TYPE:
|
serialization_options
|
Serialization options for the result (Runtime.callFunctionOn).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CallFunctionOnResponse
|
The result of the script execution.
TYPE:
|
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:
|
class_name
|
CSS class name to match.
TYPE:
|
name
|
Element name attribute value.
TYPE:
|
tag_name
|
HTML tag name (e.g., "div", "input").
TYPE:
|
text
|
Text content to match within element.
TYPE:
|
timeout
|
Maximum seconds to wait for elements to appear.
TYPE:
|
find_all
|
If True, returns all matches; if False, first match only.
TYPE:
|
raise_exc
|
Whether to raise exception if no elements found.
TYPE:
|
**attributes
|
Additional HTML attributes to match.
TYPE:
|
| 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
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:
|
timeout
|
Maximum seconds to wait for elements to appear.
TYPE:
|
find_all
|
If True, returns all matches; if False, first match only.
TYPE:
|
raise_exc
|
Whether to raise exception if no elements found.
TYPE:
|
| 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
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.
TYPE:
|
arguments
|
CDP call arguments passed positionally to the function.
TYPE:
|
execution_context_id
|
Run in this execution context of the frame (for
example an isolated world created with
TYPE:
|
| 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
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:
|
timeout
|
Seconds to wait for the browser's answer.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
T_CommandResponse
|
The browser's response, with the domain result under |
| RAISES | DESCRIPTION |
|---|---|
CommandFailed
|
If the browser answers with an error. |
CommandExecutionTimeout
|
If no answer arrives within |