Struct ElementHandle

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

ElementHandle represents an in-page DOM element. ElementHandles can be created with the [method: Page.querySelector] method.

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

(async () => {
 const browser = await chromium.launch();
 const page = await browser.newPage();
 await page.goto('https://example.com');
 const hrefElement = await page.$('a');
 await hrefElement.click();
 // ...
})();

ElementHandle prevents DOM element from garbage collection unless the handle is disposed with [method: JSHandle.dispose]. ElementHandles are auto-disposed when their origin frame gets navigated.

ElementHandle instances can be used as an argument in [method: Page.evalOnSelector] and [method: Page.evaluate] methods.

Implementations§

Source§

impl ElementHandle

Source

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

The method finds an element matching the specified selector in the ElementHandle’s subtree. If no elements match the selector, returns null.

Source

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

The method finds all elements matching the specified selector in the ElementHandles subtree. If no elements match the selector, returns empty array.

Source

pub async fn inner_text(&self) -> Result<String, Arc<Error>>

Returns the element.innerText.

Source

pub async fn inner_html(&self) -> Result<String, Arc<Error>>

Returns the element.innerHTML.

Source

pub async fn is_checked(&self) -> Result<bool, Arc<Error>>

Source

pub async fn is_disabled(&self) -> Result<bool, Arc<Error>>

Source

pub async fn is_editable(&self) -> Result<bool, Arc<Error>>

Source

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

Source

pub async fn is_hidden(&self) -> Result<bool, Arc<Error>>

Source

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

Source

pub async fn owner_frame(&self) -> Result<Option<Frame>, Arc<Error>>

Returns the frame containing the given element.

Source

pub async fn content_frame(&self) -> Result<Option<Frame>, Arc<Error>>

Returns the content frame for element handles referencing iframe nodes, or null otherwise

Source

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

Returns element attribute value.

Source

pub async fn text_content(&self) -> Result<Option<String>, Arc<Error>>

Returns the node.textContent.

Source

pub fn hover_builder(&self) -> HoverBuilder

This method hovers over the element by performing the following steps:

  1. Wait for actionability checks on the element, unless force option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.mouse] to hover over the center of the element, or the specified position.
  4. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

If the element is detached from the DOM at any moment during the action, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Source

pub fn click_builder(&self) -> ClickBuilder

Source

pub fn dblclick_builder(&self) -> DblClickBuilder

This method double clicks an element matching selector by performing the following steps:

  1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
  2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to double click in the center of the element, or the specified position.
  5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set. Note that if the first click of the dblclick() triggers a navigation event, this method will throw.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

NOTE: frame.dblclick() dispatches two click events and a single dblclick event.

Source

pub fn check_builder(&self) -> CheckBuilder

This method checks the element by performing the following steps:

  1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
  2. Wait for actionability checks on the element, unless force option is set.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element.
  5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
  6. Ensure that the element is now checked. If not, this method throws.

If the element is detached from the DOM at any moment during the action, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Source

pub fn uncheck_builder(&self) -> UncheckBuilder

This method checks the element by performing the following steps:

  1. Ensure that element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
  2. Wait for actionability checks on the element, unless force option is set.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element.
  5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
  6. Ensure that the element is now unchecked. If not, this method throws.

If the element is detached from the DOM at any moment during the action, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

Source

pub fn tap_builder(&self) -> TapBuilder

This method taps the element by performing the following steps:

  1. Wait for actionability checks on the element, unless force option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.touchscreen] to tap the center of the element, or the specified position.
  4. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

If the element is detached from the DOM at any moment during the action, this method throws.

When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

NOTE: elementHandle.tap() requires that the hasTouch option of the browser context be set to true.

Source

pub fn fill_builder<'a>(&self, value: &'a str) -> FillBuilder<'a>

This method waits for actionability checks, focuses the element, fills it and triggers an input event after filling. Note that you can pass an empty string to clear the input field.

If the target element is not an <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.

To send fine-grained keyboard events, use ElementHandle::type_builder

Source

pub async fn focus(&self) -> Result<(), Arc<Error>>

Calls focus on the element.

Source

pub fn type_builder<'a>(&self, text: &'a str) -> TypeBuilder<'a>

Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.

To press a special key, like Control or ArrowDown, use [method: ElementHandle.press].

await elementHandle.type('Hello'); // Types instantly
await elementHandle.type('World', {delay: 100}); // Types slower, like a user

An example of typing into a text field and then submitting the form:

const elementHandle = await page.$('input');
await elementHandle.type('some text');
await elementHandle.press('Enter');
Source

pub fn press_builder<'a>(&self, key: &'a str) -> PressBuilder<'a>

Focuses the element, and then uses [method: Keyboard.down] and [method: Keyboard.up].

key can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the key values can be found here. Examples of the keys are:

F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft.

Holding down Shift will type the text that corresponds to the key in the upper case.

If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

Shortcuts such as key: "Control+o" or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

Source

pub async fn scroll_into_view_if_needed( &self, timeout: Option<f64>, ) -> Result<(), Arc<Error>>

This method waits for actionability checks, then tries to scroll element into view, unless it is completely visible as defined by IntersectionObserver’s ratio.

Throws when elementHandle does not point to an element connected to a Document or a ShadowRoot.

Source

pub async fn select_text(&self, timeout: Option<f64>) -> Result<(), Arc<Error>>

This method waits for actionability checks, then focuses the element and selects all its text content.

Source

pub async fn bounding_box(&self) -> Result<Option<FloatRect>, Arc<Error>>

This method returns the bounding box of the element, or null if the element is not visible. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser window.

Scrolling affects the returned bonding box, similarly to Element.getBoundingClientRect. That means x and/or y may be negative.

Elements from child frames return the bounding box relative to the main frame, unlike the Element.getBoundingClientRect.

Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following snippet should click the center of the element.

const box = await elementHandle.boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
Source

pub async fn screenshot_builder(&self) -> ScreenshotBuilder<'_>

Returns the buffer with the captured screenshot.

This method waits for the actionability checks, then scrolls element into view before taking a screenshot. If the element is detached from DOM, the method throws an error.

Source

pub async fn wait_for_element_state( &self, state: ElementState, timeout: Option<f64>, ) -> Result<(), Arc<Error>>

Returns when the element satisfies the state.

Source

pub fn wait_for_selector_builder<'a>( &self, selector: &'a str, ) -> WaitForSelectorBuilder<'a>

Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn’t satisfy the condition for the timeout milliseconds, the function will throw.

This method works across navigations:

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

(async () => {
 const browser = await chromium.launch();
 const page = await browser.newPage();
 for (let currentURL of ['https://google.com', 'https://bbc.com']) {
   await page.goto(currentURL);
   const element = await page.mainFrame().waitForSelector('img');
   console.log('Loaded image: ' + await element.getAttribute('src'));
 }
 await browser.close();
})();
Source

pub async fn dispatch_event<T>( &self, type: &str, event_init: Option<T>, ) -> Result<(), Arc<Error>>
where T: Serialize,

The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is dispatched. This is equivalent to calling element.click().

await elementHandle.dispatchEvent('click');

Under the hood, it creates an instance of an event based on the given type, initializes it with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

You can also specify JSHandle as the property value if you want live objects to be passed into the event:

const dataTransfer = await page.evaluateHandle(() => new DataTransfer());
await elementHandle.dispatchEvent('dragstart', { dataTransfer });
Source

pub fn select_option_builder(&self) -> SelectOptionBuilder

This method waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

Returns the array of option values that have been successfully selected.

Triggers a change and input event once all the provided options have been selected.

handle.selectOption('blue');
handle.selectOption({ label: 'Blue' });
handle.selectOption(['red', 'green', 'blue']);
Source

pub fn set_input_files_builder(&self, file: File) -> SetInputFilesBuilder

This method expects elementHandle to point to an input element.

Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the the current working directory. For empty array, clears the selected files.

Trait Implementations§

Source§

impl Debug for ElementHandle

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for ElementHandle

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for ElementHandle

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

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.