Locator

Struct Locator 

Source
pub struct Locator<'a> { /* private fields */ }
Expand description

A locator for finding elements on a page.

Locators are lightweight handles that store selection criteria. They don’t query the DOM until an action is performed, enabling auto-waiting.

Implementations§

Source§

impl<'a> Locator<'a>

Source

pub fn click(&self) -> ClickBuilder<'_, 'a>

Click the element.

Returns a builder that can be configured with additional options, or awaited directly for a simple click.

§Examples
use viewpoint_core::Page;
use viewpoint_cdp::protocol::input::{MouseButton, modifiers};

// Simple click - await directly
page.locator("button").click().await?;

// Click with options
page.locator("button").click()
    .position(10.0, 5.0)
    .button(MouseButton::Right)
    .modifiers(modifiers::SHIFT)
    .send().await?;

// Force click without waiting for actionability
page.locator("button").click().force(true).await?;
§Options
Source

pub async fn dblclick(&self) -> Result<(), LocatorError>

Double-click the element.

§Errors

Returns an error if the element cannot be clicked.

§Panics

Panics if a visible element lacks bounding box coordinates. This should never occur as wait_for_actionable ensures visibility before returning.

Source

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

Fill the element with text (clears existing content first).

This is for input and textarea elements.

§Errors

Returns an error if the element cannot be focused or text cannot be inserted.

Source

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

Type text character by character.

Unlike fill, this types each character with keydown/keyup events. Returns a builder that can be configured with additional options, or awaited directly for simple typing.

§Examples
use std::time::Duration;
use viewpoint_core::Page;

// Simple type - await directly
page.locator("input").type_text("hello").await?;

// Type with delay between characters
page.locator("input").type_text("hello")
    .delay(Duration::from_millis(100))
    .send().await?;
§Options
Source

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

Press a key or key combination.

Examples: “Enter”, “Backspace”, “Control+a”, “Shift+Tab”

§Errors

Returns an error if the element cannot be focused or the key cannot be pressed.

Source

pub fn hover(&self) -> HoverBuilder<'_, 'a>

Hover over the element.

Returns a builder that can be configured with additional options, or awaited directly for a simple hover.

§Examples
use viewpoint_core::Page;

// Simple hover - await directly
page.locator("button").hover().await?;

// Hover with position offset
page.locator("button").hover()
    .position(10.0, 5.0)
    .send().await?;

// Force hover without waiting for actionability
page.locator("button").hover().force(true).await?;
§Options
Source

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

Focus the element.

§Errors

Returns an error if the element cannot be found or focused.

Source

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

Clear the element’s content.

§Errors

Returns an error if the element cannot be cleared.

Source

pub async fn check(&self) -> Result<(), LocatorError>

Check a checkbox or radio button.

§Errors

Returns an error if the element cannot be checked.

Source

pub async fn uncheck(&self) -> Result<(), LocatorError>

Uncheck a checkbox.

§Errors

Returns an error if the element cannot be unchecked.

Source

pub fn tap(&self) -> TapBuilder<'_, 'a>

Tap on the element (touch event).

Requires touch to be enabled via page.touchscreen().enable().

Returns a builder to configure tap options.

§Example
use viewpoint_core::Page;
use viewpoint_cdp::protocol::input::modifiers;

// Simple tap
page.locator("button").tap().send().await?;

// Tap with position offset
page.locator("button").tap().position(10.0, 5.0).send().await?;

// Tap with modifiers
page.locator("button").tap().modifiers(modifiers::SHIFT).send().await?;

// Force tap without waiting for actionability
page.locator("button").tap().force(true).send().await?;
Source

pub async fn drag_to(&self, target: &Locator<'_>) -> Result<(), LocatorError>

Drag this element to another locator.

§Arguments
  • target - The target locator to drag to.
§Example
use viewpoint_core::Page;

let source = page.locator("#draggable");
let target = page.locator("#droppable");
source.drag_to(&target).await?;
Source

pub async fn drag_to_with_options( &self, target: &Locator<'_>, source_position: Option<(f64, f64)>, target_position: Option<(f64, f64)>, steps: u32, ) -> Result<(), LocatorError>

Drag this element to another locator with options.

§Arguments
  • target - The target locator to drag to.
  • source_position - Optional offset from source element’s top-left corner.
  • target_position - Optional offset from target element’s top-left corner.
  • steps - Number of intermediate steps for smooth dragging.
Source

pub fn screenshot(&self) -> ElementScreenshotBuilder<'_, '_>

Take a screenshot of this element.

Returns a builder to configure screenshot options.

§Example
use viewpoint_core::Page;

// Capture element screenshot
let bytes = page.locator("button").screenshot().capture().await?;

// Capture and save to file
page.locator("button")
    .screenshot()
    .path("button.png")
    .capture()
    .await?;
Source§

impl Locator<'_>

Source

pub async fn highlight(&self) -> Result<(), LocatorError>

Highlight the element for debugging purposes.

This visually highlights the element with a magenta outline for 2 seconds, making it easy to verify which element is being targeted.

§Example
use std::time::Duration;
use viewpoint_core::Page;

// Highlight for default duration (2 seconds)
page.locator("button").highlight().await?;

// Highlight for custom duration
page.locator("button").highlight_for(Duration::from_secs(5)).await?;
§Errors

Returns an error if the element cannot be found or highlighted.

Source

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

Highlight the element for a specific duration.

§Arguments
  • duration - How long to show the highlight.
§Errors

Returns an error if the element cannot be found or highlighted.

Source§

impl<'a> Locator<'a>

Source

pub async fn evaluate<T: DeserializeOwned>( &self, expression: &str, ) -> Result<T, LocatorError>

Evaluate a JavaScript expression with the element as the first argument.

The element is passed as element to the expression. The expression should be a function body or expression that uses element.

§Arguments
  • expression - JavaScript expression. The element is available as element.
§Returns

The result of the JavaScript expression, or an error if evaluation fails.

§Example
use viewpoint_core::Page;

// Get the element's computed style
let color = page.locator("button")
    .evaluate::<String>("getComputedStyle(element).color")
    .await?;

// Get element dimensions
let rect = page.locator("button")
    .evaluate::<serde_json::Value>("element.getBoundingClientRect()")
    .await?;

// Modify element state
page.locator("input")
    .evaluate::<()>("element.value = 'Hello'")
    .await?;
§Errors

Returns an error if:

  • The element is not found
  • The JavaScript expression fails
  • The result cannot be deserialized to type T
Source

pub async fn evaluate_all<T: DeserializeOwned>( &self, expression: &str, ) -> Result<T, LocatorError>

Evaluate a JavaScript expression on all matching elements.

The elements are passed as elements (an array) to the expression.

§Arguments
  • expression - JavaScript expression. The elements are available as elements.
§Returns

The result of the JavaScript expression, or an error if evaluation fails.

§Example
use viewpoint_core::Page;

// Get all element IDs
let ids = page.locator("button")
    .evaluate_all::<Vec<String>>("elements.map(e => e.id)")
    .await?;

// Count visible elements
let count = page.locator(".item")
    .evaluate_all::<usize>("elements.filter(e => e.offsetParent !== null).length")
    .await?;

// Get custom data attributes
let data = page.locator("[data-test]")
    .evaluate_all::<Vec<String>>("elements.map(e => e.dataset.test)")
    .await?;
§Errors

Returns an error if:

  • The JavaScript expression fails
  • The result cannot be deserialized to type T
Source

pub async fn element_handle(&self) -> Result<ElementHandle<'a>, LocatorError>

Get a raw element handle for the first matching element.

The returned ElementHandle provides lower-level access to the DOM element and can be used for advanced operations that aren’t covered by the Locator API.

Note: Unlike locators, element handles are bound to the specific element at the time of creation. If the element is removed from the DOM, the handle becomes stale.

§Example
use viewpoint_core::Page;

let handle = page.locator("button").element_handle().await?;
let box_model = handle.box_model().await?;
println!("Element at: {:?}", box_model);
§Errors

Returns an error if the element cannot be found.

Source

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

Scroll the element into view if needed.

This scrolls the element’s parent container(s) to make the element visible.

§Example
use viewpoint_core::Page;

page.locator(".footer").scroll_into_view_if_needed().await?;
§Errors

Returns an error if the element cannot be found.

Source

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

Get the bounding box of the element.

Returns the element’s position and dimensions relative to the viewport.

§Example
use viewpoint_core::Page;

let bbox = page.locator("button").bounding_box().await?;
if let Some(box_) = bbox {
    println!("Element at ({}, {}), size {}x{}",
        box_.x, box_.y, box_.width, box_.height);
}
§Returns
  • Some(BoundingBox) if the element exists and is visible
  • None if the element exists but has no visible bounding box
§Errors

Returns an error if the element cannot be found.

Source§

impl Locator<'_>

Source

pub async fn set_input_files<P: AsRef<Path>>( &self, files: &[P], ) -> Result<(), LocatorError>

Set files on an <input type="file"> element.

This is the recommended way to upload files. Use an empty slice to clear the file selection.

§Arguments
  • files - Paths to the files to upload. Pass an empty slice to clear.
§Example
use viewpoint_core::Page;

// Set a single file
page.locator("input[type=file]").set_input_files(&["./upload.txt"]).await?;

// Set multiple files
page.locator("input[type=file]").set_input_files(&["file1.txt", "file2.txt"]).await?;

// Clear the file selection
page.locator("input[type=file]").set_input_files::<&str>(&[]).await?;
Source

pub async fn set_input_files_from_buffer( &self, files: &[FilePayload], ) -> Result<(), LocatorError>

Set files on a file input element from memory buffers.

This is useful when you want to upload files without having them on disk, such as dynamically generated content or test data.

§Example
use viewpoint_core::{Page, FilePayload};

// Upload a text file from memory
let payload = FilePayload::new("test.txt", "text/plain", b"Hello, World!".to_vec());
page.locator("input[type=file]").set_input_files_from_buffer(&[payload]).await?;

// Upload multiple files
let file1 = FilePayload::from_text("doc1.txt", "Content 1");
let file2 = FilePayload::new("data.json", "application/json", r#"{"key": "value"}"#.as_bytes().to_vec());
page.locator("input[type=file]").set_input_files_from_buffer(&[file1, file2]).await?;

// Clear files
page.locator("input[type=file]").set_input_files_from_buffer(&[]).await?;
Source§

impl<'a> Locator<'a>

Source

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

Get the text content of the first matching element.

§Errors

Returns an error if the element cannot be queried.

Source

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

Check if the element is visible.

§Errors

Returns an error if the element cannot be queried.

Source

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

Check if the element is checked (for checkboxes/radios).

§Errors

Returns an error if the element cannot be queried.

Source

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

Count matching elements.

§Errors

Returns an error if the elements cannot be queried.

Source

pub async fn all(&self) -> Result<Vec<Locator<'a>>, LocatorError>

Return all matching elements as individual locators.

Each returned locator points to a single element (via nth index).

§Example
use viewpoint_core::Page;

let items = page.locator("li").all().await?;
for item in items {
    println!("{}", item.text_content().await?.unwrap_or_default());
}
§Errors

Returns an error if the elements cannot be queried.

Source

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

Get the inner text of all matching elements.

Returns the innerText property for each element, which is the rendered text content as it appears on screen (respects CSS styling like display: none).

§Example
use viewpoint_core::Page;

let texts = page.locator("li").all_inner_texts().await?;
assert_eq!(texts, vec!["Item 1", "Item 2", "Item 3"]);
§Errors

Returns an error if the elements cannot be queried.

Source

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

Get the text content of all matching elements.

Returns the textContent property for each element, which includes all text including hidden elements.

§Example
use viewpoint_core::Page;

let texts = page.locator("li").all_text_contents().await?;
assert_eq!(texts, vec!["Item 1", "Item 2", "Item 3"]);
§Errors

Returns an error if the elements cannot be queried.

Source

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

Get the inner text of the first matching element.

Returns the innerText property, which is the rendered text content.

§Errors

Returns an error if the element cannot be queried.

Source

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

Get an attribute value from the first matching element.

§Errors

Returns an error if the element cannot be queried.

Source

pub async fn input_value(&self) -> Result<String, LocatorError>

Get the input value of a form element.

Works for <input>, <textarea>, and <select> elements.

§Errors

Returns an error if the element cannot be queried.

Source§

impl Locator<'_>

Source

pub async fn select_option(&self, option: &str) -> Result<(), LocatorError>

Select an option in a <select> element by value, label, or index.

§Arguments
  • option - The option to select. Can be:
    • A string value matching the option’s value attribute
    • A string matching the option’s visible text
§Errors

Returns an error if the element is not a select or the option is not found.

§Example
use viewpoint_core::Page;

// Select by value
page.locator("select#size").select_option("medium").await?;

// Select by visible text
page.locator("select#size").select_option("Medium Size").await?;
Source

pub async fn select_options(&self, options: &[&str]) -> Result<(), LocatorError>

Select multiple options in a <select multiple> element.

§Arguments
  • options - A slice of option values or labels to select.
§Errors

Returns an error if the element is not a multi-select or options are not found.

Source§

impl<'a> Locator<'a>

Source

pub fn page(&self) -> &'a Page

Get the page this locator belongs to.

Source

pub fn selector(&self) -> &Selector

Get the selector.

Source

pub fn options(&self) -> &LocatorOptions

Get the options.

Source

pub fn timeout(self, timeout: Duration) -> Self

Set a custom timeout for this locator.

Source

pub fn locator(&self, selector: impl Into<String>) -> Locator<'a>

Create a child locator that further filters elements.

§Example
use viewpoint_core::Page;

let items = page.locator(".list").locator(".item");
Source

pub fn first(&self) -> Locator<'a>

Select the first matching element.

Source

pub fn last(&self) -> Locator<'a>

Select the last matching element.

Source

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

Select the nth matching element (0-indexed).

Source

pub fn and(&self, other: Locator<'a>) -> Locator<'a>

Create a locator that matches elements that match both this locator and other.

§Example
use viewpoint_core::{Page, AriaRole};

// Find visible buttons with specific text
let button = page.get_by_role(AriaRole::Button).build()
    .and(page.get_by_text("Submit"));
Source

pub fn or(&self, other: Locator<'a>) -> Locator<'a>

Create a locator that matches elements that match either this locator or other.

§Example
use viewpoint_core::{Page, AriaRole};

// Find buttons or links
let clickable = page.get_by_role(AriaRole::Button).build()
    .or(page.get_by_role(AriaRole::Link).build());
Source

pub fn filter(&self) -> FilterBuilder<'a>

Create a filter builder to narrow down the elements matched by this locator.

§Example
use viewpoint_core::Page;

// Filter list items by text
let item = page.locator("li").filter().has_text("Product");

// Filter by having a child element
let rows = page.locator("tr").filter().has(page.locator(".active"));
Source

pub async fn aria_snapshot(&self) -> Result<AriaSnapshot, LocatorError>

Get an ARIA accessibility snapshot of this element.

The snapshot captures the accessible tree structure as it would be exposed to assistive technologies. This is useful for accessibility testing.

§Example
use viewpoint_core::Page;

let snapshot = page.locator("form").aria_snapshot().await?;
println!("{}", snapshot); // YAML-like output
§Errors

Returns an error if the element is not found or snapshot capture fails.

Trait Implementations§

Source§

impl<'a> Clone for Locator<'a>

Source§

fn clone(&self) -> Locator<'a>

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<'a> Debug for Locator<'a>

Source§

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

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

impl<'a> From<RoleLocatorBuilder<'a>> for Locator<'a>

Source§

fn from(builder: RoleLocatorBuilder<'a>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<'a> Freeze for Locator<'a>

§

impl<'a> !RefUnwindSafe for Locator<'a>

§

impl<'a> Send for Locator<'a>

§

impl<'a> Sync for Locator<'a>

§

impl<'a> Unpin for Locator<'a>

§

impl<'a> !UnwindSafe for Locator<'a>

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