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
impl ElementHandle
Sourcepub async fn query_selector(
&self,
selector: &str,
) -> Result<Option<ElementHandle>, Arc<Error>>
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
.
Sourcepub async fn query_selector_all(
&self,
selector: &str,
) -> Result<Vec<ElementHandle>, Arc<Error>>
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 ElementHandle
s subtree.
If no elements match the selector, returns empty array.
pub async fn is_checked(&self) -> Result<bool, Arc<Error>>
pub async fn is_disabled(&self) -> Result<bool, Arc<Error>>
pub async fn is_editable(&self) -> Result<bool, Arc<Error>>
pub async fn is_enabled(&self) -> Result<bool, Arc<Error>>
pub async fn is_visible(&self) -> Result<bool, Arc<Error>>
Sourcepub async fn owner_frame(&self) -> Result<Option<Frame>, Arc<Error>>
pub async fn owner_frame(&self) -> Result<Option<Frame>, Arc<Error>>
Returns the frame containing the given element.
Sourcepub async fn content_frame(&self) -> Result<Option<Frame>, Arc<Error>>
pub async fn content_frame(&self) -> Result<Option<Frame>, Arc<Error>>
Returns the content frame for element handles referencing iframe nodes, or null
otherwise
Sourcepub async fn get_attribute(
&self,
name: &str,
) -> Result<Option<String>, Arc<Error>>
pub async fn get_attribute( &self, name: &str, ) -> Result<Option<String>, Arc<Error>>
Returns element attribute value.
Sourcepub async fn text_content(&self) -> Result<Option<String>, Arc<Error>>
pub async fn text_content(&self) -> Result<Option<String>, Arc<Error>>
Returns the node.textContent
.
Sourcepub fn hover_builder(&self) -> HoverBuilder
pub fn hover_builder(&self) -> HoverBuilder
This method hovers over the element by performing the following steps:
- Wait for actionability checks on the element, unless
force
option is set. - Scroll the element into view if needed.
- Use [
property: Page.mouse
] to hover over the center of the element, or the specifiedposition
. - 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.
pub fn click_builder(&self) -> ClickBuilder
Sourcepub fn dblclick_builder(&self) -> DblClickBuilder
pub fn dblclick_builder(&self) -> DblClickBuilder
This method double clicks an element matching selector
by performing the following steps:
- Find an element matching
selector
. If there is none, wait until a matching element is attached to the DOM. - 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. - Scroll the element into view if needed.
- Use [
property: Page.mouse
] to double click in the center of the element, or the specifiedposition
. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfter
option is set. Note that if the first click of thedblclick()
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 twoclick
events and a singledblclick
event.
Sourcepub fn check_builder(&self) -> CheckBuilder
pub fn check_builder(&self) -> CheckBuilder
This method checks the element by performing the following steps:
- 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.
- Wait for actionability checks on the element, unless
force
option is set. - Scroll the element into view if needed.
- Use [
property: Page.mouse
] to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfter
option is set. - 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.
Sourcepub fn uncheck_builder(&self) -> UncheckBuilder
pub fn uncheck_builder(&self) -> UncheckBuilder
This method checks the element by performing the following steps:
- 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.
- Wait for actionability checks on the element, unless
force
option is set. - Scroll the element into view if needed.
- Use [
property: Page.mouse
] to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfter
option is set. - 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.
Sourcepub fn tap_builder(&self) -> TapBuilder
pub fn tap_builder(&self) -> TapBuilder
This method taps the element by performing the following steps:
- Wait for actionability checks on the element, unless
force
option is set. - Scroll the element into view if needed.
- Use [
property: Page.touchscreen
] to tap the center of the element, or the specifiedposition
. - 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 thehasTouch
option of the browser context be set to true.
Sourcepub fn fill_builder<'a>(&self, value: &'a str) -> FillBuilder<'a>
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
Sourcepub fn type_builder<'a>(&self, text: &'a str) -> TypeBuilder<'a>
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');
Sourcepub fn press_builder<'a>(&self, key: &'a str) -> PressBuilder<'a>
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.
Sourcepub async fn scroll_into_view_if_needed(
&self,
timeout: Option<f64>,
) -> Result<(), Arc<Error>>
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.
Sourcepub async fn select_text(&self, timeout: Option<f64>) -> Result<(), Arc<Error>>
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.
Sourcepub async fn bounding_box(&self) -> Result<Option<FloatRect>, Arc<Error>>
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);
Sourcepub async fn screenshot_builder(&self) -> ScreenshotBuilder<'_>
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.
Sourcepub async fn wait_for_element_state(
&self,
state: ElementState,
timeout: Option<f64>,
) -> Result<(), Arc<Error>>
pub async fn wait_for_element_state( &self, state: ElementState, timeout: Option<f64>, ) -> Result<(), Arc<Error>>
Returns when the element satisfies the state
.
Sourcepub fn wait_for_selector_builder<'a>(
&self,
selector: &'a str,
) -> WaitForSelectorBuilder<'a>
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();
})();
Sourcepub async fn dispatch_event<T>(
&self,
type: &str,
event_init: Option<T>,
) -> Result<(), Arc<Error>>where
T: Serialize,
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 });
Sourcepub fn select_option_builder(&self) -> SelectOptionBuilder
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']);
Sourcepub fn set_input_files_builder(&self, file: File) -> SetInputFilesBuilder
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.