ElementHandle

Struct ElementHandle 

Source
pub struct ElementHandle { /* private fields */ }

Implementations§

Source§

impl ElementHandle

Source

pub async fn click(&self) -> Result<()>

Clicks the element (left button).

Source

pub async fn left_click(&self) -> Result<()>

Left-clicks the element.

Source

pub async fn right_click(&self) -> Result<()>

Right-clicks the element.

Source

pub async fn hover(&self) -> Result<MousePosition>

Moves the mouse to the element center and returns the resulting pointer position.

Source

pub async fn move_mouse_to(&self) -> Result<MousePosition>

Semantic alias for Self::hover.

Source

pub async fn double_click(&self) -> Result<()>

Double-clicks the element.

Source

pub async fn press_and_hold(&self, duration: Duration) -> Result<()>

Presses and holds the element for the provided duration using the left mouse button.

Source

pub async fn press_and_hold_until<F, Fut>( &self, options: PressHoldOptions, condition: F, ) -> Result<bool>
where F: FnMut() -> Fut + Send, Fut: Future<Output = Result<bool>> + Send,

Presses and holds the element until the provided condition returns true or the configured timeout elapses.

Source

pub async fn text_content(&self) -> Result<String>

Gets the text content of the element.

Source

pub async fn type_text(&self, text: &str) -> Result<()>

Inserts the entire text payload into the element in a single CDP call.

The element is focused before invoking Input.insertText, which means the input behaves like a fast paste action instead of character-by-character typing.

§Parameters
  • text - The text to insert.
§Examples
if let Some(input) = page.query_selector("input[type='text']").await? {
    input.type_text("Hello, World!").await?;
}
Source

pub async fn upload_files<P>( &self, files: impl IntoIterator<Item = P>, ) -> Result<()>
where P: AsRef<Path>,

Opens the file chooser dialog and populates it with the provided paths.

Source

pub async fn clear(&self) -> Result<()>

Clears the element’s value or selection state (input, textarea, select, form, and contentEditable are supported).

This implementation mimics real user interactions where possible:

  • Text inputs and textareas reset value = "" and emit input / change
  • Checkboxes and radio buttons are unchecked
  • Select elements drop the active selection
  • ContentEditable nodes erase their HTML contents
  • Form elements recursively clear all editable descendants

Returns an error when an <input type="file"> is encountered to match browser-level restrictions.

Source

pub async fn type_text_with_delay( &self, text: &str, min_delay_ms: u64, max_delay_ms: u64, ) -> Result<()>

Types the provided text character by character while applying a random delay between each keystroke.

The element is first focused and then receives keyDown/keyUp events for every character. The delay for each character is randomly chosen within [min_delay_ms, max_delay_ms].

§Parameters
  • text - Text to type into the element.
  • min_delay_ms - Minimum delay (milliseconds) between characters.
  • max_delay_ms - Maximum delay (milliseconds) between characters.
§Examples
if let Some(input) = page.query_selector("input[type='text']").await? {
    input.type_text_with_delay("Hello, World!", 50, 150).await?;
}
Source

pub async fn get_attribute( &self, attribute_name: &str, ) -> Result<Option<String>>

Gets the value of an attribute on the element, if present.

§Parameters
  • attribute_name - The attribute to read (for example id, class, data-value).
§Returns
  • Some(String) when the attribute is defined.
  • None when the attribute is missing or resolves to null.
§Examples
if let Some(element) = page.query_selector("div.example").await? {
    if let Some(id) = element.get_attribute("id").await? {
        println!("Element ID: {}", id);
    }
    if let Some(data_value) = element.get_attribute("data-value").await? {
        println!("Data value: {}", data_value);
    }
}
Source

pub async fn get_html(&self) -> Result<String>

Gets the element’s outer HTML (including its own tag).

§Returns

The full HTML string representing the element and its descendants.

§Examples
if let Some(element) = page.query_selector("div.example").await? {
    let html = element.get_html().await?;
    println!("Element HTML: {}", html);
}
Source

pub async fn screenshot(&self, save_path: Option<PathBuf>) -> Result<String>

Takes a screenshot of the element.

§Parameters
  • save_path - Optional file path (including file name). When None, a timestamped file such as element_screenshot_<ts>.png is created in the current working directory.
§Returns

The path where the screenshot was saved.

§Notes
  • Uses the default border box, which generally works well for rounded elements.
  • Automatically adapts to the device pixel ratio (DPR) for crisp images.
  • Use screenshot_with_options for additional control.
§Examples
if let Some(element) = page.query_selector("div.example").await? {
    // Save to the current directory (with DPR auto-adjust)
    let path = element.screenshot(None).await?;
    println!("Element screenshot saved to: {}", path);

    // Save to a custom location
    let path = element.screenshot(Some("screenshots/element.png".into())).await?;
    println!("Element screenshot saved to: {}", path);
}
Source

pub async fn screenshot_with_options( &self, save_path: Option<PathBuf>, box_type: ScreenshotBoxType, auto_resolve_dpr: bool, ) -> Result<String>

Takes a screenshot of the element with a custom box type.

§Parameters
  • save_path - Optional file path (including file name).
  • box_type - Bounding box strategy that determines the capture region.
  • auto_resolve_dpr - Whether to adapt the screenshot to the device pixel ratio (true is recommended for high-DPI displays).
§Bounding Box Types
  • Content: Captures only the content area, excluding padding.

    • Best for: screenshots that should omit interior padding.
    • Less ideal when padding needs to remain visible.
  • Padding: Captures content and padding, excluding the border.

    • Best for: including interior spacing while omitting borders.
    • Less ideal when borders or rounded corners must be preserved.
  • Border (default): Captures content, padding, and border.

    • Ideal for rounded corners (border-radius).
    • Suitable for elements where the border defines the visual shape.
    • Works well for most everyday use cases.
  • Margin: Captures content, padding, border, and margin.

    • Best for: including surrounding whitespace in the capture.
    • Less ideal when margins introduce too much empty space.
§Returns

The path where the screenshot was saved.

§Examples
if let Some(element) = page.query_selector("button.rounded").await? {
    // Rounded button with border box + DPR auto adjustment (recommended)
    let path = element.screenshot_with_options(
        Some("button.png".into()),
        ScreenshotBoxType::Border,
        true  // enable DPR auto adjustment
    ).await?;

    // Content-only capture with DPR adaptation disabled
    let path = element.screenshot_with_options(
        Some("content.png".into()),
        ScreenshotBoxType::Content,
        false  // fixed scale = 1.0
    ).await?;

    // Include the margin while keeping DPR auto adjustment
    let path = element.screenshot_with_options(
        Some("with-margin.png".into()),
        ScreenshotBoxType::Margin,
        true
    ).await?;
}
Source

pub async fn is_visible(&self) -> Result<bool>

Determines whether the element is visible.

The element is considered visible when:

  • It is present in the DOM tree.
  • It does not use display: none or visibility: hidden (and opacity is not 0).
  • Its rendered bounding box is non-zero.
§Returns

true if the element is visible, otherwise false.

§Examples
let element = page.query_selector("#my-element").await?.unwrap();
if element.is_visible().await? {
    println!("Element is visible");
}
Source

pub async fn is_enabled(&self) -> Result<bool>

Checks whether the element is enabled (not disabled).

§Returns

true when the element is enabled, otherwise false.

Source

pub async fn is_clickable(&self) -> Result<bool>

Determines whether the element can be clicked.

The element is considered clickable when it is visible, enabled, and not occluded by another element at its center point.

§Returns

true if the element is clickable, otherwise false.

Source

pub async fn wait_for_visible(&self, timeout_ms: Option<u64>) -> Result<()>

Waits for the element to become visible.

§Parameters
  • timeout_ms - Timeout in milliseconds (defaults to 30000).
§Examples
let element = page.query_selector("#dynamic-content").await?.unwrap();
element.wait_for_visible(Some(5000)).await?;
Source

pub async fn wait_for_hidden(&self, timeout_ms: Option<u64>) -> Result<()>

Waits for the element to become hidden.

§Parameters
  • timeout_ms - Timeout in milliseconds (defaults to 30000).
Source

pub async fn wait_for_clickable(&self, timeout_ms: Option<u64>) -> Result<()>

Waits for the element to become clickable.

§Parameters
  • timeout_ms - Timeout in milliseconds (defaults to 30000).
§Examples
let button = page.query_selector("#submit-btn").await?.unwrap();
button.wait_for_clickable(Some(5000)).await?;
button.click().await?;
Source

pub async fn wait_for_enabled(&self, timeout_ms: Option<u64>) -> Result<()>

Waits for the element to become enabled (not disabled).

§Parameters
  • timeout_ms - Timeout in milliseconds (defaults to 30000).
Source

pub async fn shadow_root(&self) -> Result<Option<ShadowRoot>>

Retrieves the element’s shadow root (supports both open and closed modes).

§Returns
  • Ok(Some(ShadowRoot)) when the element exposes a shadow root.
  • Ok(None) when the element has no shadow root.
  • Err(_) if the operation failed.
§Examples
let host = page.query_selector("#shadow-host").await?.unwrap();

if let Some(shadow_root) = host.shadow_root().await? {
    // Query inside the shadow DOM
    let inner = shadow_root.query_selector(".inner-element").await?;
}
Source

pub async fn query_selector_shadow( &self, selector: &str, ) -> Result<Option<ElementHandle>>

Queries for a single element inside the shadow DOM (supports open and closed modes).

This is a convenience wrapper around element.shadow_root().await?.query_selector(selector).

§Parameters
  • selector - CSS selector.
§Returns
  • Ok(Some(ElementHandle)) when a matching element is found.
  • Ok(None) when the element has no shadow root or no match is located.
  • Err(_) if querying fails.
§Examples
let host = page.query_selector("#shadow-host").await?.unwrap();

if let Some(inner) = host.query_selector_shadow(".inner-element").await? {
    let text = inner.text_content().await?;
    println!("Shadow DOM content: {}", text);
}
Source

pub async fn query_selector_all_shadow( &self, selector: &str, ) -> Result<Vec<ElementHandle>>

Queries for all matching elements within the shadow DOM (supports open and closed modes).

§Parameters
  • selector - CSS selector used for the lookup.
§Returns

A vector of matching elements, or an empty vector when no shadow root is present.

§Examples
let host = page.query_selector("#shadow-host").await?.unwrap();

let items = host.query_selector_all_shadow(".list-item").await?;
println!("Found {} items in Shadow DOM", items.len());

Trait Implementations§

Source§

impl Clone for ElementHandle

Source§

fn clone(&self) -> ElementHandle

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more