Skip to main content

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_rs::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 get_by_text() - find elements by text content
    let _ = page.goto(
        "data:text/html,<button>Submit</button><button>Submit Order</button>",
        None
    ).await;
    let all_submits = page.get_by_text("Submit", false).await;
    assert_eq!(all_submits.count().await?, 2); // case-insensitive substring
    let exact_submit = page.get_by_text("Submit", true).await;
    assert_eq!(exact_submit.count().await?, 1); // exact match only

    // Demonstrate get_by_label, get_by_placeholder, get_by_test_id
    let _ = page.goto(
        "data:text/html,<label for='email'>Email</label>\
            <input id='email' placeholder='you@example.com' data-testid='email-input' />",
        None
    ).await;
    let by_label = page.get_by_label("Email", false).await;
    assert_eq!(by_label.count().await?, 1);
    let by_placeholder = page.get_by_placeholder("you@example.com", true).await;
    assert_eq!(by_placeholder.count().await?, 1);
    let by_test_id = page.get_by_test_id("email-input").await;
    assert_eq!(by_test_id.count().await?, 1);

    // 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 page(&self) -> Result<Page>

Returns the Page this locator belongs to.

Each locator is bound to the page that created it. Chained locators (via first(), last(), nth(), locator(), filter(), etc.) all return the same owning page. This matches the behavior of locator.page in other Playwright language bindings.

§Example
let playwright = Playwright::launch().await?;
let browser = playwright.chromium().launch().await?;
let page = browser.new_page().await?;
page.goto("https://example.com", None).await?;

let locator = page.locator("h1").await;
let locator_page = locator.page()?;
assert_eq!(locator_page.url(), page.url());

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

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 get_by_text(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements containing the given text.

By default, matching is case-insensitive and searches for a substring. Set exact to true for case-sensitive exact matching.

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

Source

pub fn get_by_label(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their associated label text.

Targets form controls (input, textarea, select) linked via <label>, aria-label, or aria-labelledby.

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

Source

pub fn get_by_placeholder(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their placeholder text.

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

Source

pub fn get_by_alt_text(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their alt text.

Typically used for <img> elements.

See: https://playwright.dev/docs/api/class-locator#locator-get-by-alt-text

Source

pub fn get_by_title(&self, text: &str, exact: bool) -> Locator

Returns a locator that matches elements by their title attribute.

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

Source

pub fn get_by_test_id(&self, test_id: &str) -> Locator

Returns a locator that matches elements by their data-testid attribute.

Always uses exact matching (case-sensitive).

See: https://playwright.dev/docs/api/class-locator#locator-get-by-test-id

Source

pub fn get_by_role( &self, role: AriaRole, options: Option<GetByRoleOptions>, ) -> Locator

Returns a locator that matches elements by their ARIA role.

This is the recommended way to locate elements, as it matches the way users and assistive technology perceive the page.

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

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 fn filter(&self, options: FilterOptions) -> Locator

Narrows this locator according to the filter options.

Can be chained to apply multiple filters in sequence.

§Example
use playwright_rs::{Playwright, FilterOptions};

let playwright = Playwright::launch().await?;
let browser = playwright.chromium().launch().await?;
let page = browser.new_page().await?;

// Filter rows to those containing "Apple"
let rows = page.locator("tr").await;
let apple_row = rows.filter(FilterOptions {
    has_text: Some("Apple".to_string()),
    ..Default::default()
});

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

Source

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

Creates a locator matching elements that satisfy both this locator and locator.

Note: named and_ because and is a Rust keyword.

§Example
use playwright_rs::Playwright;

let playwright = Playwright::launch().await?;
let browser = playwright.chromium().launch().await?;
let page = browser.new_page().await?;

// Find a button that also has a specific title
let button = page.locator("button").await;
let titled = page.locator("[title='Subscribe']").await;
let subscribe_btn = button.and_(&titled);

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

Source

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

Creates a locator matching elements that satisfy either this locator or locator.

Note: named or_ because or is a Rust keyword.

§Example
use playwright_rs::Playwright;

let playwright = Playwright::launch().await?;
let browser = playwright.chromium().launch().await?;
let page = browser.new_page().await?;

// Find any element that is either a button or a link
let buttons = page.locator("button").await;
let links = page.locator("a").await;
let interactive = buttons.or_(&links);

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

Source

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

Returns the number of elements matching this locator.

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

Source

pub async fn all(&self) -> Result<Vec<Locator>>

Returns an array of locators, one for each matching element.

Note: all() does not wait for elements to match the locator, and instead immediately returns whatever is in the DOM.

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

Source

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

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>

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>

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

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>

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>

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>

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>

Returns whether the element is editable.

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

Source

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

Returns whether the element is hidden.

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

Source

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

Returns whether the element is disabled.

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

Source

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

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<()>

Source

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

Source

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

Source

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

Source

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

Source

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

Sets focus on the element.

Calls the element’s focus() method. Used to move keyboard focus to a specific element for subsequent keyboard interactions.

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

Source

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

Removes focus from the element.

Calls the element’s blur() method. Moves keyboard focus away from the element.

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

Source

pub async fn press_sequentially( &self, text: &str, options: Option<PressSequentiallyOptions>, ) -> Result<()>

Types text into the element character by character, as though it was typed on a real keyboard.

Use this method when you need to simulate keystrokes with individual key events (e.g., for autocomplete widgets). For simply setting a field value, prefer Locator::fill().

§Arguments
  • text - Text to type into the element
  • options - Optional [PressSequentiallyOptions] (e.g., delay between key presses)

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

Source

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

Returns the innerText values of all elements matching this locator.

Unlike Locator::inner_text() (which uses strict mode and requires exactly one match), all_inner_texts() returns text from all matching elements.

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

Source

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

Returns the textContent values of all elements matching this locator.

Unlike Locator::text_content() (which uses strict mode and requires exactly one match), all_text_contents() returns text from all matching elements.

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

Source

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

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<()>

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<()>

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<()>

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>

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

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

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<()>

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<()>

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<()>

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<()>

Sets multiple files to upload using FilePayload.

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

Source

pub async fn dispatch_event( &self, type_: &str, event_init: Option<Value>, ) -> Result<()>

Dispatches a DOM event on the element.

Unlike clicking or typing, dispatch_event directly sends the event without performing any actionability checks. It still waits for the element to be present in the DOM.

§Arguments
  • type_ - The event type to dispatch, e.g. "click", "focus", "myevent".
  • event_init - Optional event initializer properties (e.g. {"detail": "value"} for CustomEvent). Corresponds to the second argument of new Event(type, init).
§Errors

Returns an error if:

  • The element is not found within the timeout
  • The protocol call fails

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

Source

pub async fn bounding_box(&self) -> Result<Option<BoundingBox>>

Returns the bounding box of the element, or None if the element is not visible.

The bounding box is in pixels, relative to the top-left corner of the page. Returns None when the element has display: none or is otherwise not part of the layout.

§Errors

Returns an error if:

  • The element is not found within the timeout
  • The protocol call fails

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

Source

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

Scrolls the element into view if it is not already visible in the viewport.

This is an alias for calling element.scrollIntoView() in the browser.

§Errors

Returns an error if:

  • The element is not found within the timeout
  • The protocol call fails

See: https://playwright.dev/docs/api/class-locator#locator-scroll-into-view-if-needed

Source

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

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

Source

pub async fn tap(&self, options: Option<TapOptions>) -> Result<()>

Performs a touch-tap on the element.

This method dispatches a touchstart and touchend event on the element. For touch support to work, the browser context must be created with has_touch: true.

§Arguments
  • options - Optional [TapOptions] (force, modifiers, position, timeout, trial)
§Errors

Returns an error if:

  • The element is not found within the timeout
  • Actionability checks fail (unless force: true)
  • The browser context was not created with has_touch: true

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

Source

pub async fn drag_to( &self, target: &Locator, options: Option<DragToOptions>, ) -> Result<()>

Drags this element to the target element.

Both this locator and target must resolve to elements in the same frame. Playwright performs a series of mouse events (move, press, move to target, release) to simulate the drag.

§Arguments
  • target - The locator of the element to drag onto
  • options - Optional [DragToOptions] (force, no_wait_after, timeout, trial, source_position, target_position)
§Errors

Returns an error if:

  • Either element is not found within the timeout
  • Actionability checks fail (unless force: true)
  • The protocol call fails

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

Source

pub async fn wait_for(&self, options: Option<WaitForOptions>) -> Result<()>

Waits until the element satisfies the given state condition.

If no state is specified, waits for the element to be visible (the default).

This method is useful for waiting for lazy-rendered elements or elements that appear/disappear based on user interaction or async data loading.

§Arguments
  • options - Optional [WaitForOptions] specifying the state to wait for (Visible, Hidden, Attached, or Detached) and a timeout in milliseconds.
§Errors

Returns an error if the element does not satisfy the expected state within the timeout.

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

Source

pub async fn evaluate<R, T>( &self, expression: &str, arg: Option<T>, ) -> Result<R>

Evaluates a JavaScript expression in the scope of the matched element.

The element is passed as the first argument to the expression. The expression can be any JavaScript function or expression that returns a JSON-serializable value.

§Arguments
  • expression - JavaScript expression or function, e.g. "(el) => el.textContent"
  • arg - Optional argument passed as the second argument to the function
§Errors

Returns an error if:

  • The element is not found within the timeout
  • The JavaScript expression throws an error
  • The return value is not JSON-serializable
§Example
use playwright_rs::Playwright;

let playwright = Playwright::launch().await?;
let browser = playwright.chromium().launch().await?;
let page = browser.new_page().await?;
let _ = page.goto("data:text/html,<h1>Hello</h1>", None).await;

let heading = page.locator("h1").await;
let text: String = heading.evaluate("(el) => el.textContent", None::<()>).await?;
assert_eq!(text, "Hello");

// With an argument
let result: String = heading
    .evaluate("(el, suffix) => el.textContent + suffix", Some("!"))
    .await?;
assert_eq!(result, "Hello!");

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

Source

pub async fn evaluate_all<R, T>( &self, expression: &str, arg: Option<T>, ) -> Result<R>

Evaluates a JavaScript expression in the scope of all elements matching this locator.

The array of all matched elements is passed as the first argument to the expression. Unlike evaluate(), this does not use strict mode — all matching elements are collected and passed as an array.

§Arguments
  • expression - JavaScript function that receives an array of elements
  • arg - Optional argument passed as the second argument to the function
§Errors

Returns an error if:

  • The JavaScript expression throws an error
  • The return value is not JSON-serializable
§Example
use playwright_rs::Playwright;

let playwright = Playwright::launch().await?;
let browser = playwright.chromium().launch().await?;
let page = browser.new_page().await?;
let _ = page.goto(
    "data:text/html,<li class='item'>A</li><li class='item'>B</li>",
    None
).await;

let items = page.locator(".item").await;
let texts: Vec<String> = items
    .evaluate_all("(elements) => elements.map(e => e.textContent)", None::<()>)
    .await?;
assert_eq!(texts, vec!["A", "B"]);

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

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

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