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>
impl<'a> Locator<'a>
Sourcepub fn click(&self) -> ClickBuilder<'_, 'a>
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
ClickBuilder::position- Click at offset from element’s top-left cornerClickBuilder::button- Use a different mouse button (right, middle)ClickBuilder::modifiers- Hold modifier keys (Shift, Ctrl, Alt)ClickBuilder::force- Skip actionability checks
Sourcepub async fn dblclick(&self) -> Result<(), LocatorError>
pub async fn dblclick(&self) -> Result<(), LocatorError>
Sourcepub async fn fill(&self, text: &str) -> Result<(), LocatorError>
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.
Sourcepub fn type_text(&self, text: &str) -> TypeBuilder<'_, 'a>
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
TypeBuilder::delay- Add delay between character keystrokes
Sourcepub async fn press(&self, key: &str) -> Result<(), LocatorError>
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.
Sourcepub fn hover(&self) -> HoverBuilder<'_, 'a>
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
HoverBuilder::position- Hover at offset from element’s top-left cornerHoverBuilder::modifiers- Hold modifier keys during hoverHoverBuilder::force- Skip actionability checks
Sourcepub async fn focus(&self) -> Result<(), LocatorError>
pub async fn focus(&self) -> Result<(), LocatorError>
Sourcepub async fn clear(&self) -> Result<(), LocatorError>
pub async fn clear(&self) -> Result<(), LocatorError>
Sourcepub async fn check(&self) -> Result<(), LocatorError>
pub async fn check(&self) -> Result<(), LocatorError>
Sourcepub async fn uncheck(&self) -> Result<(), LocatorError>
pub async fn uncheck(&self) -> Result<(), LocatorError>
Sourcepub fn tap(&self) -> TapBuilder<'_, 'a>
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?;Sourcepub async fn drag_to_with_options(
&self,
target: &Locator<'_>,
source_position: Option<(f64, f64)>,
target_position: Option<(f64, f64)>,
steps: u32,
) -> Result<(), LocatorError>
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.
Sourcepub fn screenshot(&self) -> ElementScreenshotBuilder<'_, '_>
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<'_>
impl Locator<'_>
Sourcepub async fn highlight(&self) -> Result<(), LocatorError>
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.
Sourcepub async fn highlight_for(
&self,
duration: Duration,
) -> Result<(), LocatorError>
pub async fn highlight_for( &self, duration: Duration, ) -> Result<(), LocatorError>
Source§impl<'a> Locator<'a>
impl<'a> Locator<'a>
Sourcepub async fn evaluate<T: DeserializeOwned>(
&self,
expression: &str,
) -> Result<T, LocatorError>
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 aselement.
§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
Sourcepub async fn evaluate_all<T: DeserializeOwned>(
&self,
expression: &str,
) -> Result<T, LocatorError>
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 aselements.
§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
Sourcepub async fn element_handle(&self) -> Result<ElementHandle<'a>, LocatorError>
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.
Sourcepub async fn scroll_into_view_if_needed(&self) -> Result<(), LocatorError>
pub async fn scroll_into_view_if_needed(&self) -> Result<(), LocatorError>
Sourcepub async fn bounding_box(&self) -> Result<Option<BoundingBox>, LocatorError>
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 visibleNoneif the element exists but has no visible bounding box
§Errors
Returns an error if the element cannot be found.
Source§impl Locator<'_>
impl Locator<'_>
Sourcepub async fn set_input_files<P: AsRef<Path>>(
&self,
files: &[P],
) -> Result<(), LocatorError>
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?;Sourcepub async fn set_input_files_from_buffer(
&self,
files: &[FilePayload],
) -> Result<(), LocatorError>
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>
impl<'a> Locator<'a>
Sourcepub async fn text_content(&self) -> Result<Option<String>, LocatorError>
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.
Sourcepub async fn is_visible(&self) -> Result<bool, LocatorError>
pub async fn is_visible(&self) -> Result<bool, LocatorError>
Sourcepub async fn is_checked(&self) -> Result<bool, LocatorError>
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.
Sourcepub async fn count(&self) -> Result<usize, LocatorError>
pub async fn count(&self) -> Result<usize, LocatorError>
Sourcepub async fn all(&self) -> Result<Vec<Locator<'a>>, LocatorError>
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.
Sourcepub async fn all_inner_texts(&self) -> Result<Vec<String>, LocatorError>
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.
Sourcepub async fn all_text_contents(&self) -> Result<Vec<String>, LocatorError>
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.
Sourcepub async fn inner_text(&self) -> Result<String, LocatorError>
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.
Sourcepub async fn get_attribute(
&self,
name: &str,
) -> Result<Option<String>, LocatorError>
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.
Sourcepub async fn input_value(&self) -> Result<String, LocatorError>
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<'_>
impl Locator<'_>
Sourcepub async fn select_option(&self, option: &str) -> Result<(), LocatorError>
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
valueattribute - A string matching the option’s visible text
- A string value matching the option’s
§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?;Sourcepub async fn select_options(&self, options: &[&str]) -> Result<(), LocatorError>
pub async fn select_options(&self, options: &[&str]) -> Result<(), LocatorError>
Source§impl<'a> Locator<'a>
impl<'a> Locator<'a>
Sourcepub fn options(&self) -> &LocatorOptions
pub fn options(&self) -> &LocatorOptions
Get the options.
Sourcepub fn locator(&self, selector: impl Into<String>) -> Locator<'a>
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");Sourcepub fn and(&self, other: Locator<'a>) -> Locator<'a>
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"));Sourcepub fn or(&self, other: Locator<'a>) -> Locator<'a>
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());Sourcepub fn filter(&self) -> FilterBuilder<'a>
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"));Sourcepub async fn aria_snapshot(&self) -> Result<AriaSnapshot, LocatorError>
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.