Locator

Struct Locator 

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

Locator represents a way to find element(s) on the page at any given moment.

Locators are lazy - they don’t execute queries until an action is performed. This enables auto-waiting and retry-ability for robust test automation.

§Examples

use playwright_core::protocol::{Playwright, SelectOption};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let playwright = Playwright::launch().await?;
    let browser = playwright.chromium().launch().await?;
    let page = browser.new_page().await?;

    // Demonstrate set_checked() - checkbox interaction
    let _ = page.goto(
        "data:text/html,<input type='checkbox' id='cb'>",
        None
    ).await;
    let checkbox = page.locator("#cb").await;
    checkbox.set_checked(true, None).await?;
    assert!(checkbox.is_checked().await?);
    checkbox.set_checked(false, None).await?;
    assert!(!checkbox.is_checked().await?);

    // Demonstrate select_option() - select by value, label, and index
    let _ = page.goto(
        "data:text/html,<select id='fruits'>\
            <option value='apple'>Apple</option>\
            <option value='banana'>Banana</option>\
            <option value='cherry'>Cherry</option>\
        </select>",
        None
    ).await;
    let select = page.locator("#fruits").await;
    select.select_option("banana", None).await?;
    assert_eq!(select.input_value(None).await?, "banana");
    select.select_option(SelectOption::Label("Apple".to_string()), None).await?;
    assert_eq!(select.input_value(None).await?, "apple");
    select.select_option(SelectOption::Index(2), None).await?;
    assert_eq!(select.input_value(None).await?, "cherry");

    // Demonstrate select_option_multiple() - multi-select
    let _ = page.goto(
        "data:text/html,<select id='colors' multiple>\
            <option value='red'>Red</option>\
            <option value='green'>Green</option>\
            <option value='blue'>Blue</option>\
            <option value='yellow'>Yellow</option>\
        </select>",
        None
    ).await;
    let multi = page.locator("#colors").await;
    let selected = multi.select_option_multiple(&["red", "blue"], None).await?;
    assert_eq!(selected.len(), 2);
    assert!(selected.contains(&"red".to_string()));
    assert!(selected.contains(&"blue".to_string()));

    // Demonstrate screenshot() - element screenshot
    let _ = page.goto(
        "data:text/html,<h1 id='title'>Hello World</h1>",
        None
    ).await;
    let heading = page.locator("#title").await;
    let screenshot = heading.screenshot(None).await?;
    assert!(!screenshot.is_empty());

    browser.close().await?;
    Ok(())
}

See: https://playwright.dev/docs/api/class-locator

Implementations§

Source§

impl Locator

Source

pub fn selector(&self) -> &str

Returns the selector string for this locator

Source

pub fn first(&self) -> Locator

Creates a locator for the first matching element.

See: https://playwright.dev/docs/api/class-locator#locator-first

Source

pub fn last(&self) -> Locator

Creates a locator for the last matching element.

See: https://playwright.dev/docs/api/class-locator#locator-last

Source

pub fn nth(&self, index: i32) -> Locator

Creates a locator for the nth matching element (0-indexed).

See: https://playwright.dev/docs/api/class-locator#locator-nth

Source

pub fn locator(&self, selector: &str) -> Locator

Creates a sub-locator within this locator’s subtree.

See: https://playwright.dev/docs/api/class-locator#locator-locator

Source

pub async fn count(&self) -> Result<usize, Error>

Returns the number of elements matching this locator.

See: https://playwright.dev/docs/api/class-locator#locator-count

Source

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

Returns the text content of the element.

See: https://playwright.dev/docs/api/class-locator#locator-text-content

Source

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

Returns the inner text of the element (visible text).

See: https://playwright.dev/docs/api/class-locator#locator-inner-text

Source

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

Returns the inner HTML of the element.

See: https://playwright.dev/docs/api/class-locator#locator-inner-html

Source

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

Returns the value of the specified attribute.

See: https://playwright.dev/docs/api/class-locator#locator-get-attribute

Source

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

Returns whether the element is visible.

See: https://playwright.dev/docs/api/class-locator#locator-is-visible

Source

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

Returns whether the element is enabled.

See: https://playwright.dev/docs/api/class-locator#locator-is-enabled

Source

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

Returns whether the checkbox or radio button is checked.

See: https://playwright.dev/docs/api/class-locator#locator-is-checked

Source

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

Returns whether the element is editable.

See: https://playwright.dev/docs/api/class-locator#locator-is-editable

Source

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

Returns whether the element is focused (currently has focus).

See: https://playwright.dev/docs/api/class-locator#locator-is-focused

Source

pub async fn click(&self, options: Option<ClickOptions>) -> Result<(), Error>

Source

pub async fn dblclick(&self, options: Option<ClickOptions>) -> Result<(), Error>

Source

pub async fn fill( &self, text: &str, options: Option<FillOptions>, ) -> Result<(), Error>

Source

pub async fn clear(&self, options: Option<FillOptions>) -> Result<(), Error>

Source

pub async fn press( &self, key: &str, options: Option<PressOptions>, ) -> Result<(), Error>

Source

pub async fn check(&self, options: Option<CheckOptions>) -> Result<(), Error>

Ensures the checkbox or radio button is checked.

This method is idempotent - if already checked, does nothing.

See: https://playwright.dev/docs/api/class-locator#locator-check

Source

pub async fn uncheck(&self, options: Option<CheckOptions>) -> Result<(), Error>

Ensures the checkbox is unchecked.

This method is idempotent - if already unchecked, does nothing.

See: https://playwright.dev/docs/api/class-locator#locator-uncheck

Source

pub async fn set_checked( &self, checked: bool, options: Option<CheckOptions>, ) -> Result<(), Error>

Sets the checkbox or radio button to the specified checked state.

This is a convenience method that calls check() if checked is true, or uncheck() if checked is false.

See: https://playwright.dev/docs/api/class-locator#locator-set-checked

Source

pub async fn hover(&self, options: Option<HoverOptions>) -> Result<(), Error>

Hovers the mouse over the element.

See: https://playwright.dev/docs/api/class-locator#locator-hover

Source

pub async fn input_value(&self, _options: Option<()>) -> Result<String, Error>

Returns the value of the input, textarea, or select element.

See: https://playwright.dev/docs/api/class-locator#locator-input-value

Source

pub async fn select_option( &self, value: impl Into<SelectOption>, options: Option<SelectOptions>, ) -> Result<Vec<String>, Error>

Selects one or more options in a select element.

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

See: https://playwright.dev/docs/api/class-locator#locator-select-option

Source

pub async fn select_option_multiple( &self, values: &[impl Into<SelectOption> + Clone], options: Option<SelectOptions>, ) -> Result<Vec<String>, Error>

Selects multiple options in a select element.

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

See: https://playwright.dev/docs/api/class-locator#locator-select-option

Source

pub async fn set_input_files( &self, file: &PathBuf, _options: Option<()>, ) -> Result<(), Error>

Sets the file path(s) to upload to a file input element.

See: https://playwright.dev/docs/api/class-locator#locator-set-input-files

Source

pub async fn set_input_files_multiple( &self, files: &[&PathBuf], _options: Option<()>, ) -> Result<(), Error>

Sets multiple file paths to upload to a file input element.

See: https://playwright.dev/docs/api/class-locator#locator-set-input-files

Source

pub async fn set_input_files_payload( &self, file: FilePayload, _options: Option<()>, ) -> Result<(), Error>

Sets a file to upload using FilePayload (explicit name, mimeType, buffer).

See: https://playwright.dev/docs/api/class-locator#locator-set-input-files

Source

pub async fn set_input_files_payload_multiple( &self, files: &[FilePayload], _options: Option<()>, ) -> Result<(), Error>

Sets multiple files to upload using FilePayload.

See: https://playwright.dev/docs/api/class-locator#locator-set-input-files

Source

pub async fn screenshot( &self, options: Option<ScreenshotOptions>, ) -> Result<Vec<u8>, Error>

Takes a screenshot of the element and returns the image bytes.

This method uses strict mode - it will fail if the selector matches multiple elements. Use first(), last(), or nth() to refine the selector to a single element.

See: https://playwright.dev/docs/api/class-locator#locator-screenshot

Trait Implementations§

Source§

impl Clone for Locator

Source§

fn clone(&self) -> Locator

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
Source§

impl Debug for Locator

Source§

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

Formats the value using the given formatter. 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> 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<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