class: Locator
Added in: v1.14
Locators are the central piece of copilotbrowser's auto-waiting and retry-ability. In a nutshell, locators represent a way to find element(s) on the page at any moment. A locator can be created with the Page.locator() method.
async method: Locator.all
Added in: v1.29 Returns:
Array<Locator>
When the locator points to a list of elements, this returns an array of locators, pointing to their respective elements.
Locator.all() does not wait for elements to match the locator, and instead immediately returns whatever is present in the page.
When the list of elements changes dynamically, Locator.all() will produce unpredictable and flaky results.
When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before calling Locator.all().
Usage
for (const li of await page.getByRole('listitem').all())
await li.click();
for li in await page.get_by_role('listitem').all():
await li.click();
for li in page.get_by_role('listitem').all():
li.click();
for (Locator li : page.getByRole("listitem").all())
li.click();
foreach (var li in await page.GetByRole("listitem").AllAsync())
await li.ClickAsync();
async method: Locator.allInnerTexts
Added in: v1.14 Returns:
Array<string>
Returns an array of node.innerText values for all matching nodes.
If you need to assert text on the page, prefer LocatorAssertions.toHaveText() with LocatorAssertions.toHaveText.useInnerText option to avoid flakiness. See assertions guide for more details.
Usage
const texts = await page.getByRole('link').allInnerTexts();
texts = await page.get_by_role("link").all_inner_texts()
texts = page.get_by_role("link").all_inner_texts()
String[] texts = page.getByRole(AriaRole.LINK).allInnerTexts();
var texts = await page.GetByRole(AriaRole.Link).AllInnerTextsAsync();
async method: Locator.allTextContents
Added in: v1.14 Returns:
Array<string>
Returns an array of node.textContent values for all matching nodes.
If you need to assert text on the page, prefer LocatorAssertions.toHaveText() to avoid flakiness. See assertions guide for more details.
Usage
const texts = await page.getByRole('link').allTextContents();
texts = await page.get_by_role("link").all_text_contents()
texts = page.get_by_role("link").all_text_contents()
String[] texts = page.getByRole(AriaRole.LINK).allTextContents();
var texts = await page.GetByRole(AriaRole.Link).AllTextContentsAsync();
method: Locator.and
Added in: v1.34
Languages: (all) Returns:
Locator
Creates a locator that matches both this locator and the argument locator.
Usage
The following example finds a button with a specific title.
const button = page.getByRole('button').and(page.getByTitle('Subscribe'));
Locator button = page.getByRole(AriaRole.BUTTON).and(page.getByTitle("Subscribe"));
button = page.get_by_role("button").and_(page.get_by_title("Subscribe"))
button = page.get_by_role("button").and_(page.get_by_title("Subscribe"))
var button = page.GetByRole(AriaRole.Button).And(page.GetByTitle("Subscribe"));
param: Locator.and.locator
Added in: v1.34
locator<Locator>
Additional locator to match.
async method: Locator.ariaSnapshot
Added in: v1.49 Returns:
string
Captures the aria snapshot of the given element. Read more about aria snapshots and LocatorAssertions.toMatchAriaSnapshot() for the corresponding assertion.
Usage
await page.getByRole('link').ariaSnapshot();
page.getByRole(AriaRole.LINK).ariaSnapshot();
await page.get_by_role("link").aria_snapshot()
page.get_by_role("link").aria_snapshot()
await page.GetByRole(AriaRole.Link).AriaSnapshotAsync();
Details
This method captures the aria snapshot of the given element. The snapshot is a string that represents the state of the element and its children. The snapshot can be used to assert the state of the element in the test, or to compare it to state in the future.
The ARIA snapshot is represented using YAML markup language:
- The keys of the objects are the roles and optional accessible names of the elements.
- The values are either text content or an array of child elements.
- Generic static text can be represented with the
textkey.
Below is the HTML markup and the respective ARIA snapshot:
<ul aria-label="Links">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<ul>
- list "Links":
- listitem:
- link "Home"
- listitem:
- link "About"
option: Locator.ariaSnapshot.timeout = %%-input-timeout-%%
Added in: v1.49
option: Locator.ariaSnapshot.timeout = %%-input-timeout-js-%%
Added in: v1.49
async method: Locator.blur
Added in: v1.28
Calls blur on the element.
option: Locator.blur.timeout = %%-input-timeout-%%
Added in: v1.28
option: Locator.blur.timeout = %%-input-timeout-js-%%
Added in: v1.28
async method: Locator.boundingBox
Added in: v1.14 Returns:
null|Object
x<float> the x coordinate of the element in pixels.y<float> the y coordinate of the element in pixels.width<float> the width of the element in pixels.height<float> the height of the element in pixels.
This method returns the bounding box of the element matching the locator, 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.
Details
Scrolling affects the returned bounding 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.
Usage
const box = await page.getByRole('button').boundingBox();
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
BoundingBox box = page.getByRole(AriaRole.BUTTON).boundingBox();
page.mouse().click(box.x + box.width / 2, box.y + box.height / 2);
box = await page.get_by_role("button").bounding_box()
await page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
box = page.get_by_role("button").bounding_box()
page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
var box = await page.GetByRole(AriaRole.Button).BoundingBoxAsync();
await page.Mouse.ClickAsync(box.X + box.Width / 2, box.Y + box.Height / 2);
option: Locator.boundingBox.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.boundingBox.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.check
Added in: v1.14
Ensure that checkbox or radio element is checked.
Details
Performs 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 Page.mouse to click in the center of the element.
- 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.
Usage
await page.getByRole('checkbox').check();
page.getByRole(AriaRole.CHECKBOX).check();
await page.get_by_role("checkbox").check()
page.get_by_role("checkbox").check()
await page.GetByRole(AriaRole.Checkbox).CheckAsync();
option: Locator.check.position = %%-input-position-%%
Added in: v1.14
option: Locator.check.force = %%-input-force-%%
Added in: v1.14
option: Locator.check.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.check.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.check.timeout = %%-input-timeout-js-%%
Added in: v1.14
option: Locator.check.trial = %%-input-trial-%%
Added in: v1.14
async method: Locator.clear
Added in: v1.28
Clear the input field.
Details
This method waits for actionability checks, focuses the element, clears it and triggers an input event after clearing.
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 cleared instead.
Usage
await page.getByRole('textbox').clear();
page.getByRole(AriaRole.TEXTBOX).clear();
await page.get_by_role("textbox").clear()
page.get_by_role("textbox").clear()
await page.GetByRole(AriaRole.Textbox).ClearAsync();
option: Locator.clear.force = %%-input-force-%%
Added in: v1.28
option: Locator.clear.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.28
option: Locator.clear.timeout = %%-input-timeout-%%
Added in: v1.28
option: Locator.clear.timeout = %%-input-timeout-js-%%
Added in: v1.28
async method: Locator.click
Added in: v1.14
Click an element.
Details
This method clicks 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 Page.mouse to click in the center of the element, or the specified position.
- 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.
Usage
Click a button:
await page.getByRole('button').click();
page.getByRole(AriaRole.BUTTON).click();
await page.get_by_role("button").click()
page.get_by_role("button").click()
await page.GetByRole(AriaRole.Button).ClickAsync();
Shift-right-click at a specific position on a canvas:
await page.locator('canvas').click({
button: 'right',
modifiers: ['Shift'],
position: { x: 23, y: 32 },
});
page.locator("canvas").click(new Locator.ClickOptions()
.setButton(MouseButton.RIGHT)
.setModifiers(Arrays.asList(KeyboardModifier.SHIFT))
.setPosition(23, 32));
await page.locator("canvas").click(
button="right", modifiers=["Shift"], position={"x": 23, "y": 32}
)
page.locator("canvas").click(
button="right", modifiers=["Shift"], position={"x": 23, "y": 32}
)
await page.Locator("canvas").ClickAsync(new() {
Button = MouseButton.Right,
Modifiers = new[] { KeyboardModifier.Shift },
Position = new Position { X = 0, Y = 0 }
});
option: Locator.click.button = %%-input-button-%%
Added in: v1.14
option: Locator.click.clickCount = %%-input-click-count-%%
Added in: v1.14
option: Locator.click.delay = %%-input-down-up-delay-%%
Added in: v1.14
option: Locator.click.position = %%-input-position-%%
Added in: v1.14
option: Locator.click.modifiers = %%-input-modifiers-%%
Added in: v1.14
option: Locator.click.force = %%-input-force-%%
Added in: v1.14
option: Locator.click.noWaitAfter = %%-input-no-wait-after-%%
Added in: v1.14
option: Locator.click.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.click.timeout = %%-input-timeout-js-%%
Added in: v1.14
option: Locator.click.trial = %%-input-trial-with-modifiers-%%
Added in: v1.14
option: Locator.click.steps = %%-input-mousemove-steps-%%
Added in: v1.57
async method: Locator.count
Added in: v1.14 Returns:
int
Returns the number of elements matching the locator.
If you need to assert the number of elements on the page, prefer LocatorAssertions.toHaveCount() to avoid flakiness. See assertions guide for more details.
Usage
const count = await page.getByRole('listitem').count();
count = await page.get_by_role("listitem").count()
count = page.get_by_role("listitem").count()
int count = page.getByRole(AriaRole.LISTITEM).count();
int count = await page.GetByRole(AriaRole.Listitem).CountAsync();
async method: Locator.dblclick
Added in: v1.14
Languages: (all)
Double-click an element.
Details
This method double clicks 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 Page.mouse to double click in the center of the element, or the specified position.
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.
element.dblclick() dispatches two click events and a single dblclick event.
option: Locator.dblclick.button = %%-input-button-%%
Added in: v1.14
option: Locator.dblclick.delay = %%-input-down-up-delay-%%
Added in: v1.14
option: Locator.dblclick.position = %%-input-position-%%
Added in: v1.14
option: Locator.dblclick.modifiers = %%-input-modifiers-%%
Added in: v1.14
option: Locator.dblclick.force = %%-input-force-%%
Added in: v1.14
option: Locator.dblclick.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.dblclick.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.dblclick.timeout = %%-input-timeout-js-%%
Added in: v1.14
option: Locator.dblclick.trial = %%-input-trial-with-modifiers-%%
Added in: v1.14
option: Locator.dblclick.steps = %%-input-mousemove-steps-%%
Added in: v1.57
method: Locator.describe
Added in: v1.53 Returns:
Locator
Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the same element.
Usage
const button = page.getByTestId('btn-sub').describe('Subscribe button');
await button.click();
Locator button = page.getByTestId("btn-sub").describe("Subscribe button");
button.click();
button = page.get_by_test_id("btn-sub").describe("Subscribe button")
await button.click()
button = page.get_by_test_id("btn-sub").describe("Subscribe button")
button.click()
var button = Page.GetByTestId("btn-sub").Describe("Subscribe button");
await button.ClickAsync();
param: Locator.describe.description
Added in: v1.53
description<string>
Locator description.
method: Locator.description
Added in: v1.57
Languages: Python, Java, C# Returns:
null|string
Returns locator description previously set with Locator.describe(). Returns null if no custom description has been set.
Usage
button = page.get_by_role("button").describe("Subscribe button")
print(button.description()) # "Subscribe button"
input = page.get_by_role("textbox")
print(input.description()) # None
button = page.get_by_role("button").describe("Subscribe button")
print(button.description()) # "Subscribe button"
input = page.get_by_role("textbox")
print(input.description()) # None
Locator button = page.getByRole(AriaRole.BUTTON).describe("Subscribe button");
System.out.println(button.description()); // "Subscribe button"
Locator input = page.getByRole(AriaRole.TEXTBOX);
System.out.println(input.description()); // null
var button = Page.GetByRole(AriaRole.Button).Describe("Subscribe button");
Console.WriteLine(button.Description()); // "Subscribe button"
var input = Page.GetByRole(AriaRole.Textbox);
Console.WriteLine(input.Description()); // null
method: Locator.description
Added in: v1.57
Languages: JavaScript Returns:
null|string
Returns locator description previously set with Locator.describe(). Returns null if no custom description has been set. Prefer Locator.toString() for a human-readable representation, as it uses the description when available.
Usage
const button = page.getByRole('button').describe('Subscribe button');
console.log(button.description()); // "Subscribe button"
const input = page.getByRole('textbox');
console.log(input.description()); // null
async method: Locator.dispatchEvent
Added in: v1.14
Programmatically dispatch an event on the matching element.
Usage
await locator.dispatchEvent('click');
locator.dispatchEvent("click");
await locator.dispatch_event("click")
locator.dispatch_event("click")
await locator.DispatchEventAsync("click");
Details
The snippet above 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().
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:
- DeviceMotionEvent
- DeviceOrientationEvent
- DragEvent
- Event
- FocusEvent
- KeyboardEvent
- MouseEvent
- PointerEvent
- TouchEvent
- WheelEvent
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 locator.dispatchEvent('dragstart', { dataTransfer });
JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
locator.dispatchEvent("dragstart", arg);
data_transfer = await page.evaluate_handle("new DataTransfer()")
await locator.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer})
data_transfer = page.evaluate_handle("new DataTransfer()")
locator.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer})
var dataTransfer = await page.EvaluateHandleAsync("() => new DataTransfer()");
await locator.DispatchEventAsync("dragstart", new Dictionary<string, object>
{
{ "dataTransfer", dataTransfer }
});
param: Locator.dispatchEvent.type
Added in: v1.14
type<string>
DOM event type: "click", "dragstart", etc.
param: Locator.dispatchEvent.eventInit
Added in: v1.14
eventInit?<EvaluationArgument>
Optional event-specific initialization properties.
option: Locator.dispatchEvent.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.dispatchEvent.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.dragTo
Added in: v1.18
Drag the source element towards the target element and drop it.
Details
This method drags the locator to another target locator or target position. It will
first move to the source element, perform a mousedown, then move to the target
element or position and perform a mouseup.
Usage
const source = page.locator('#source');
const target = page.locator('#target');
await source.dragTo(target);
// or specify exact positions relative to the top-left corners of the elements:
await source.dragTo(target, {
sourcePosition: { x: 34, y: 7 },
targetPosition: { x: 10, y: 20 },
});
Locator source = page.locator("#source");
Locator target = page.locator("#target");
source.dragTo(target);
// or specify exact positions relative to the top-left corners of the elements:
source.dragTo(target, new Locator.DragToOptions()
.setSourcePosition(34, 7).setTargetPosition(10, 20));
source = page.locator("#source")
target = page.locator("#target")
await source.drag_to(target)
# or specify exact positions relative to the top-left corners of the elements:
await source.drag_to(
target,
source_position={"x": 34, "y": 7},
target_position={"x": 10, "y": 20}
)
source = page.locator("#source")
target = page.locator("#target")
source.drag_to(target)
# or specify exact positions relative to the top-left corners of the elements:
source.drag_to(
target,
source_position={"x": 34, "y": 7},
target_position={"x": 10, "y": 20}
)
var source = Page.Locator("#source");
var target = Page.Locator("#target");
await source.DragToAsync(target);
// or specify exact positions relative to the top-left corners of the elements:
await source.DragToAsync(target, new()
{
SourcePosition = new() { X = 34, Y = 7 },
TargetPosition = new() { X = 10, Y = 20 },
});
param: Locator.dragTo.target
Added in: v1.18
target<Locator>
Locator of the element to drag to.
option: Locator.dragTo.force = %%-input-force-%%
Added in: v1.18
option: Locator.dragTo.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.18
option: Locator.dragTo.timeout = %%-input-timeout-%%
Added in: v1.18
option: Locator.dragTo.timeout = %%-input-timeout-js-%%
Added in: v1.18
option: Locator.dragTo.trial = %%-input-trial-%%
Added in: v1.18
option: Locator.dragTo.sourcePosition = %%-input-source-position-%%
Added in: v1.18
option: Locator.dragTo.targetPosition = %%-input-target-position-%%
Added in: v1.18
option: Locator.dragTo.steps = %%-input-drag-steps-%%
Added in: v1.57
async method: Locator.elementHandle
Added in: v1.14
- discouraged: Always prefer using
Locators and web assertions overElementHandles because latter are inherently racy. Returns:ElementHandle
Resolves given locator to the first matching DOM element. If there are no matching elements, waits for one. If multiple elements match the locator, throws.
option: Locator.elementHandle.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.elementHandle.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.elementHandles
Added in: v1.14
- discouraged: Always prefer using
Locators and web assertions overElementHandles because latter are inherently racy. Returns:Array<ElementHandle>
Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
method: Locator.contentFrame
Added in: v1.43 Returns:
FrameLocator
Returns a FrameLocator object pointing to the same iframe as this locator.
Useful when you have a Locator object obtained somewhere, and later on would like to interact with the content inside the frame.
For a reverse operation, use FrameLocator.owner().
Usage
const locator = page.locator('iframe[name="embedded"]');
// ...
const frameLocator = locator.contentFrame();
await frameLocator.getByRole('button').click();
Locator locator = page.locator("iframe[name=\"embedded\"]");
// ...
FrameLocator frameLocator = locator.contentFrame();
frameLocator.getByRole(AriaRole.BUTTON).click();
locator = page.locator("iframe[name=\"embedded\"]")
# ...
frame_locator = locator.content_frame
await frame_locator.get_by_role("button").click()
locator = page.locator("iframe[name=\"embedded\"]")
# ...
frame_locator = locator.content_frame
frame_locator.get_by_role("button").click()
var locator = Page.Locator("iframe[name=\"embedded\"]");
// ...
var frameLocator = locator.ContentFrame;
await frameLocator.GetByRole(AriaRole.Button).ClickAsync();
async method: Locator.evaluate
Added in: v1.14 Returns:
Serializable
Execute JavaScript code in the page, taking the matching element as an argument.
Details
Returns the return value of expression, called with the matching element as a first argument, and arg as a second argument.
If expression returns a Promise, this method will wait for the promise to resolve and return its value.
If expression throws or rejects, this method throws.
Usage
Passing argument to expression:
const result = await page.getByTestId('myId').evaluate((element, [x, y]) => {
return element.textContent + ' ' + x * y;
}, [7, 8]);
console.log(result); // prints "myId text 56"
Object result = page.getByTestId("myId").evaluate("(element, [x, y]) => {\n" +
" return element.textContent + ' ' + x * y;\n" +
"}", Arrays.asList(7, 8));
System.out.println(result); // prints "myId text 56"
result = await page.get_by_testid("myId").evaluate("(element, [x, y]) => element.textContent + ' ' + x * y", [7, 8])
print(result) # prints "myId text 56"
result = page.get_by_testid("myId").evaluate("(element, [x, y]) => element.textContent + ' ' + x * y", [7, 8])
print(result) # prints "myId text 56"
var result = await page.GetByTestId("myId").EvaluateAsync<string>("(element, [x, y]) => element.textContent + ' ' + x * y)", new[] { 7, 8 });
Console.WriteLine(result); // prints "myId text 56"
param: Locator.evaluate.expression = %%-evaluate-expression-%%
Added in: v1.14
param: Locator.evaluate.expression = %%-js-evaluate-pagefunction-%%
Added in: v1.14
param: Locator.evaluate.arg
Added in: v1.14
arg?<EvaluationArgument>
Optional argument to pass to expression.
option: Locator.evaluate.timeout
Added in: v1.14
Languages: Python, Java, C#
timeout<float>
Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved, evaluation itself is not limited by the timeout. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
option: Locator.evaluate.timeout
Added in: v1.14
Languages: JavaScript
timeout<float>
Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved, evaluation itself is not limited by the timeout. Defaults to 0 - no timeout.
async method: Locator.evaluateAll
Added in: v1.14 Returns:
Serializable
Execute JavaScript code in the page, taking all matching elements as an argument.
Details
Returns the return value of expression, called with an array of all matching elements as a first argument, and arg as a second argument.
If expression returns a Promise, this method will wait for the promise to resolve and return its value.
If expression throws or rejects, this method throws.
Usage
const locator = page.locator('div');
const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10);
Locator locator = page.locator("div");
boolean moreThanTen = (boolean) locator.evaluateAll("(divs, min) => divs.length > min", 10);
locator = page.locator("div")
more_than_ten = await locator.evaluate_all("(divs, min) => divs.length > min", 10)
locator = page.locator("div")
more_than_ten = locator.evaluate_all("(divs, min) => divs.length > min", 10)
var locator = page.Locator("div");
var moreThanTen = await locator.EvaluateAllAsync<bool>("(divs, min) => divs.length > min", 10);
param: Locator.evaluateAll.expression = %%-evaluate-expression-%%
Added in: v1.14
param: Locator.evaluateAll.expression = %%-js-evaluate-pagefunction-%%
Added in: v1.14
param: Locator.evaluateAll.arg
Added in: v1.14
arg?<EvaluationArgument>
Optional argument to pass to expression.
async method: Locator.evaluateHandle
Added in: v1.14 Returns:
JSHandle
Execute JavaScript code in the page, taking the matching element as an argument, and return a JSHandle with the result.
Details
Returns the return value of expression as a[JSHandle], called with the matching element as a first argument, and arg as a second argument.
The only difference between Locator.evaluate() and Locator.evaluateHandle() is that Locator.evaluateHandle() returns JSHandle.
If expression returns a Promise, this method will wait for the promise to resolve and return its value.
If expression throws or rejects, this method throws.
See Page.evaluateHandle() for more details.
param: Locator.evaluateHandle.expression = %%-evaluate-expression-%%
Added in: v1.14
param: Locator.evaluateHandle.expression = %%-js-evaluate-pagefunction-%%
Added in: v1.14
param: Locator.evaluateHandle.arg
Added in: v1.14
arg?<EvaluationArgument>
Optional argument to pass to expression.
option: Locator.evaluateHandle.timeout
Added in: v1.14
Languages: Python, Java, C#
timeout<float>
Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved, evaluation itself is not limited by the timeout. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
option: Locator.evaluateHandle.timeout
Added in: v1.14
Languages: JavaScript
timeout<float>
Maximum time in milliseconds to wait for the locator before evaluating. Note that after locator is resolved, evaluation itself is not limited by the timeout. Defaults to 0 - no timeout.
async method: Locator.fill
Added in: v1.14
Set a value to the input field.
Usage
await page.getByRole('textbox').fill('example value');
page.getByRole(AriaRole.TEXTBOX).fill("example value");
await page.get_by_role("textbox").fill("example value")
page.get_by_role("textbox").fill("example value")
await page.GetByRole(AriaRole.Textbox).FillAsync("example value");
Details
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 Locator.pressSequentially().
param: Locator.fill.value
Added in: v1.14
value<string>
Value to set for the <input>, <textarea> or [contenteditable] element.
option: Locator.fill.force = %%-input-force-%%
Added in: v1.14
option: Locator.fill.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.fill.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.fill.timeout = %%-input-timeout-js-%%
Added in: v1.14
method: Locator.filter
Added in: v1.22 Returns:
Locator
This method narrows existing locator according to the options, for example filters by text. It can be chained to filter multiple times.
Usage
const rowLocator = page.locator('tr');
// ...
await rowLocator
.filter({ hasText: 'text in column 1' })
.filter({ has: page.getByRole('button', { name: 'column 2 button' }) })
.screenshot();
Locator rowLocator = page.locator("tr");
// ...
rowLocator
.filter(new Locator.FilterOptions().setHasText("text in column 1"))
.filter(new Locator.FilterOptions().setHas(
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("column 2 button"))
))
.screenshot();
row_locator = page.locator("tr")
# ...
await row_locator.filter(has_text="text in column 1").filter(
has=page.get_by_role("button", name="column 2 button")
).screenshot()
row_locator = page.locator("tr")
# ...
row_locator.filter(has_text="text in column 1").filter(
has=page.get_by_role("button", name="column 2 button")
).screenshot()
var rowLocator = page.Locator("tr");
// ...
await rowLocator
.Filter(new() { HasText = "text in column 1" })
.Filter(new() {
Has = page.GetByRole(AriaRole.Button, new() { Name = "column 2 button" } )
})
.ScreenshotAsync();
option: Locator.filter.-inline- = %%-locator-options-list-v1.14-%%
Added in: v1.22
option: Locator.filter.hasNot = %%-locator-option-has-not-%%
Added in: v1.33
option: Locator.filter.hasNotText = %%-locator-option-has-not-text-%%
Added in: v1.33
option: Locator.filter.visible = %%-locator-option-visible-%%
Added in: v1.51
method: Locator.first
Added in: v1.14 Returns:
Locator
Returns locator to the first matching element.
async method: Locator.focus
Added in: v1.14
Calls focus on the matching element.
option: Locator.focus.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.focus.timeout = %%-input-timeout-js-%%
Added in: v1.14
method: Locator.frameLocator
Added in: v1.17 Returns:
FrameLocator
When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in that iframe:
Usage
const locator = page.frameLocator('iframe').getByText('Submit');
await locator.click();
Locator locator = page.frameLocator("iframe").getByText("Submit");
locator.click();
locator = page.frame_locator("iframe").get_by_text("Submit")
await locator.click()
locator = page.frame_locator("iframe").get_by_text("Submit")
locator.click()
var locator = page.FrameLocator("iframe").GetByText("Submit");
await locator.ClickAsync();
param: Locator.frameLocator.selector = %%-find-selector-%%
Added in: v1.17
async method: Locator.getAttribute
Added in: v1.14 Returns:
null|string
Returns the matching element's attribute value.
If you need to assert an element's attribute, prefer LocatorAssertions.toHaveAttribute() to avoid flakiness. See assertions guide for more details.
param: Locator.getAttribute.name
Added in: v1.14
name<string>
Attribute name to get the value for.
option: Locator.getAttribute.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.getAttribute.timeout = %%-input-timeout-js-%%
Added in: v1.14
method: Locator.getByAltText
Added in: v1.27 Returns:
Locator
%%-template-locator-get-by-alt-text-%%
param: Locator.getByAltText.text = %%-locator-get-by-text-text-%%
option: Locator.getByAltText.exact = %%-locator-get-by-text-exact-%%
method: Locator.getByLabel
Added in: v1.27 Returns:
Locator
%%-template-locator-get-by-label-text-%%
param: Locator.getByLabel.text = %%-locator-get-by-text-text-%%
option: Locator.getByLabel.exact = %%-locator-get-by-text-exact-%%
method: Locator.getByPlaceholder
Added in: v1.27 Returns:
Locator
%%-template-locator-get-by-placeholder-text-%%
param: Locator.getByPlaceholder.text = %%-locator-get-by-text-text-%%
option: Locator.getByPlaceholder.exact = %%-locator-get-by-text-exact-%%
method: Locator.getByRole
Added in: v1.27 Returns:
Locator
%%-template-locator-get-by-role-%%
param: Locator.getByRole.role = %%-get-by-role-to-have-role-role-%%
Added in: v1.27
option: Locator.getByRole.-inline- = %%-locator-get-by-role-option-list-v1.27-%%
Added in: v1.27
option: Locator.getByRole.exact = %%-locator-get-by-role-option-exact-%%
method: Locator.getByTestId
Added in: v1.27 Returns:
Locator
%%-template-locator-get-by-test-id-%%
param: Locator.getByTestId.testId = %%-locator-get-by-test-id-test-id-%%
Added in: v1.27
method: Locator.getByText
Added in: v1.27 Returns:
Locator
%%-template-locator-get-by-text-%%
param: Locator.getByText.text = %%-locator-get-by-text-text-%%
option: Locator.getByText.exact = %%-locator-get-by-text-exact-%%
method: Locator.getByTitle
Added in: v1.27 Returns:
Locator
%%-template-locator-get-by-title-%%
param: Locator.getByTitle.text = %%-locator-get-by-text-text-%%
option: Locator.getByTitle.exact = %%-locator-get-by-text-exact-%%
async method: Locator.highlight
Added in: v1.20
Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses Locator.highlight().
async method: Locator.hover
Added in: v1.14
Hover over the matching element.
Usage
await page.getByRole('link').hover();
await page.get_by_role("link").hover()
page.get_by_role("link").hover()
page.getByRole(AriaRole.LINK).hover();
await page.GetByRole(AriaRole.Link).HoverAsync();
Details
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 Page.mouse to hover over the center of the element, or the specified position.
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.
option: Locator.hover.position = %%-input-position-%%
Added in: v1.14
option: Locator.hover.modifiers = %%-input-modifiers-%%
Added in: v1.14
option: Locator.hover.force = %%-input-force-%%
Added in: v1.14
option: Locator.hover.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.hover.timeout = %%-input-timeout-js-%%
Added in: v1.14
option: Locator.hover.trial = %%-input-trial-with-modifiers-%%
Added in: v1.14
option: Locator.hover.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.28
async method: Locator.innerHTML
Added in: v1.14 Returns:
string
Returns the element.innerHTML.
option: Locator.innerHTML.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.innerHTML.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.innerText
Added in: v1.14 Returns:
string
Returns the element.innerText.
If you need to assert text on the page, prefer LocatorAssertions.toHaveText() with LocatorAssertions.toHaveText.useInnerText option to avoid flakiness. See assertions guide for more details.
option: Locator.innerText.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.innerText.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.inputValue
Added in: v1.14 Returns:
string
Returns the value for the matching <input> or <textarea> or <select> element.
If you need to assert input value, prefer LocatorAssertions.toHaveValue() to avoid flakiness. See assertions guide for more details.
Usage
const value = await page.getByRole('textbox').inputValue();
value = await page.get_by_role("textbox").input_value()
value = page.get_by_role("textbox").input_value()
String value = page.getByRole(AriaRole.TEXTBOX).inputValue();
String value = await page.GetByRole(AriaRole.Textbox).InputValueAsync();
Details
Throws elements that are not an input, textarea or a select. However, if the element is inside the <label> element that has an associated control, returns the value of the control.
option: Locator.inputValue.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.inputValue.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.isChecked
Added in: v1.14 Returns:
boolean
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
If you need to assert that checkbox is checked, prefer LocatorAssertions.toBeChecked() to avoid flakiness. See assertions guide for more details.
Usage
const checked = await page.getByRole('checkbox').isChecked();
boolean checked = page.getByRole(AriaRole.CHECKBOX).isChecked();
checked = await page.get_by_role("checkbox").is_checked()
checked = page.get_by_role("checkbox").is_checked()
var isChecked = await page.GetByRole(AriaRole.Checkbox).IsCheckedAsync();
option: Locator.isChecked.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.isChecked.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.isDisabled
Added in: v1.14 Returns:
boolean
Returns whether the element is disabled, the opposite of enabled.
If you need to assert that an element is disabled, prefer LocatorAssertions.toBeDisabled() to avoid flakiness. See assertions guide for more details.
Usage
const disabled = await page.getByRole('button').isDisabled();
boolean disabled = page.getByRole(AriaRole.BUTTON).isDisabled();
disabled = await page.get_by_role("button").is_disabled()
disabled = page.get_by_role("button").is_disabled()
Boolean disabled = await page.GetByRole(AriaRole.Button).IsDisabledAsync();
option: Locator.isDisabled.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.isDisabled.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.isEditable
Added in: v1.14 Returns:
boolean
Returns whether the element is editable. If the target element is not an <input>, <textarea>, <select>, [contenteditable] and does not have a role allowing [aria-readonly], this method throws an error.
If you need to assert that an element is editable, prefer LocatorAssertions.toBeEditable() to avoid flakiness. See assertions guide for more details.
Usage
const editable = await page.getByRole('textbox').isEditable();
boolean editable = page.getByRole(AriaRole.TEXTBOX).isEditable();
editable = await page.get_by_role("textbox").is_editable()
editable = page.get_by_role("textbox").is_editable()
Boolean editable = await page.GetByRole(AriaRole.Textbox).IsEditableAsync();
option: Locator.isEditable.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.isEditable.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.isEnabled
Added in: v1.14 Returns:
boolean
Returns whether the element is enabled.
If you need to assert that an element is enabled, prefer LocatorAssertions.toBeEnabled() to avoid flakiness. See assertions guide for more details.
Usage
const enabled = await page.getByRole('button').isEnabled();
boolean enabled = page.getByRole(AriaRole.BUTTON).isEnabled();
enabled = await page.get_by_role("button").is_enabled()
enabled = page.get_by_role("button").is_enabled()
Boolean enabled = await page.GetByRole(AriaRole.Button).IsEnabledAsync();
option: Locator.isEnabled.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.isEnabled.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.isHidden
Added in: v1.14 Returns:
boolean
Returns whether the element is hidden, the opposite of visible.
If you need to assert that element is hidden, prefer LocatorAssertions.toBeHidden() to avoid flakiness. See assertions guide for more details.
Usage
const hidden = await page.getByRole('button').isHidden();
boolean hidden = page.getByRole(AriaRole.BUTTON).isHidden();
hidden = await page.get_by_role("button").is_hidden()
hidden = page.get_by_role("button").is_hidden()
Boolean hidden = await page.GetByRole(AriaRole.Button).IsHiddenAsync();
option: Locator.isHidden.timeout
Added in: v1.14
⚠️ Deprecated. This option is ignored. Locator.isHidden() does not wait for the element to become hidden and returns immediately.
timeout<float>
async method: Locator.isVisible
Added in: v1.14 Returns:
boolean
Returns whether the element is visible.
If you need to assert that element is visible, prefer LocatorAssertions.toBeVisible() to avoid flakiness. See assertions guide for more details.
Usage
const visible = await page.getByRole('button').isVisible();
boolean visible = page.getByRole(AriaRole.BUTTON).isVisible();
visible = await page.get_by_role("button").is_visible()
visible = page.get_by_role("button").is_visible()
Boolean visible = await page.GetByRole(AriaRole.Button).IsVisibleAsync();
option: Locator.isVisible.timeout
Added in: v1.14
⚠️ Deprecated. This option is ignored. Locator.isVisible() does not wait for the element to become visible and returns immediately.
timeout<float>
method: Locator.last
Added in: v1.14 Returns:
Locator
Returns locator to the last matching element.
Usage
const banana = await page.getByRole('listitem').last();
banana = await page.get_by_role("listitem").last
banana = page.get_by_role("listitem").last
Locator banana = page.getByRole(AriaRole.LISTITEM).last();
var banana = await page.GetByRole(AriaRole.Listitem).Last(1);
method: Locator.locator
Added in: v1.14 Returns:
Locator
%%-template-locator-locator-%%
param: Locator.locator.selectorOrLocator = %%-find-selector-or-locator-%%
Added in: v1.14
option: Locator.locator.-inline- = %%-locator-options-list-v1.14-%%
Added in: v1.14
option: Locator.locator.hasNot = %%-locator-option-has-not-%%
Added in: v1.33
option: Locator.locator.hasNotText = %%-locator-option-has-not-text-%%
Added in: v1.33
method: Locator.nth
Added in: v1.14 Returns:
Locator
Returns locator to the n-th matching element. It's zero based, nth(0) selects the first element.
Usage
const banana = await page.getByRole('listitem').nth(2);
banana = await page.get_by_role("listitem").nth(2)
banana = page.get_by_role("listitem").nth(2)
Locator banana = page.getByRole(AriaRole.LISTITEM).nth(2);
var banana = await page.GetByRole(AriaRole.Listitem).Nth(2);
param: Locator.nth.index
Added in: v1.14
index<int>
method: Locator.or
Added in: v1.33
Languages: (all) Returns:
Locator
Creates a locator matching all elements that match one or both of the two locators.
Note that when both locators match something, the resulting locator will have multiple matches, potentially causing a locator strictness violation.
Usage
Consider a scenario where you'd like to click on a "New email" button, but sometimes a security settings dialog shows up instead. In this case, you can wait for either a "New email" button, or a dialog and act accordingly.
If both "New email" button and security dialog appear on screen, the "or" locator will match both of them, possibly throwing the "strict mode violation" error. In this case, you can use Locator.first() to only match one of them.
const newEmail = page.getByRole('button', { name: 'New' });
const dialog = page.getByText('Confirm security settings');
await expect(newEmail.or(dialog).first()).toBeVisible();
if (await dialog.isVisible())
await page.getByRole('button', { name: 'Dismiss' }).click();
await newEmail.click();
Locator newEmail = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("New"));
Locator dialog = page.getByText("Confirm security settings");
assertThat(newEmail.or(dialog).first()).isVisible();
if (dialog.isVisible())
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Dismiss")).click();
newEmail.click();
new_email = page.get_by_role("button", name="New")
dialog = page.get_by_text("Confirm security settings")
await expect(new_email.or_(dialog).first).to_be_visible()
if (await dialog.is_visible()):
await page.get_by_role("button", name="Dismiss").click()
await new_email.click()
new_email = page.get_by_role("button", name="New")
dialog = page.get_by_text("Confirm security settings")
expect(new_email.or_(dialog).first).to_be_visible()
if (dialog.is_visible()):
page.get_by_role("button", name="Dismiss").click()
new_email.click()
var newEmail = page.GetByRole(AriaRole.Button, new() { Name = "New" });
var dialog = page.GetByText("Confirm security settings");
await Expect(newEmail.Or(dialog).First).ToBeVisibleAsync();
if (await dialog.IsVisibleAsync())
await page.GetByRole(AriaRole.Button, new() { Name = "Dismiss" }).ClickAsync();
await newEmail.ClickAsync();
param: Locator.or.locator
Added in: v1.33
locator<Locator>
Alternative locator to match.
method: Locator.page
Added in: v1.19 Returns:
Page
A page this locator belongs to.
async method: Locator.press
Added in: v1.14
Focuses the matching element and presses a combination of the keys.
Usage
await page.getByRole('textbox').press('Backspace');
page.getByRole(AriaRole.TEXTBOX).press("Backspace");
await page.get_by_role("textbox").press("Backspace")
page.get_by_role("textbox").press("Backspace")
await page.GetByRole(AriaRole.Textbox).PressAsync("Backspace");
Details
Focuses the element, and then uses Keyboard.down() and 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, ControlOrMeta.
ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS.
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", key: "Control++ 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.
param: Locator.press.key
Added in: v1.14
key<string>
Name of the key to press or a character to generate, such as ArrowLeft or a.
option: Locator.press.delay
Added in: v1.14
delay<float>
Time to wait between keydown and keyup in milliseconds. Defaults to 0.
option: Locator.press.noWaitAfter = %%-input-no-wait-after-%%
Added in: v1.14
option: Locator.press.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.press.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.pressSequentially
Added in: v1.38
In most cases, you should use Locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page.
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 Locator.press().
Usage
await locator.pressSequentially('Hello'); // Types instantly
await locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user
locator.pressSequentially("Hello"); // Types instantly
locator.pressSequentially("World", new Locator.pressSequentiallyOptions().setDelay(100)); // Types slower, like a user
await locator.press_sequentially("hello") # types instantly
await locator.press_sequentially("world", delay=100) # types slower, like a user
locator.press_sequentially("hello") # types instantly
locator.press_sequentially("world", delay=100) # types slower, like a user
await locator.PressSequentiallyAsync("Hello"); // Types instantly
await locator.PressSequentiallyAsync("World", new() { Delay = 100 }); // Types slower, like a user
An example of typing into a text field and then submitting the form:
const locator = page.getByLabel('Password');
await locator.pressSequentially('my password');
await locator.press('Enter');
Locator locator = page.getByLabel("Password");
locator.pressSequentially("my password");
locator.press("Enter");
locator = page.get_by_label("Password")
await locator.press_sequentially("my password")
await locator.press("Enter")
locator = page.get_by_label("Password")
locator.press_sequentially("my password")
locator.press("Enter")
var locator = page.GetByLabel("Password");
await locator.PressSequentiallyAsync("my password");
await locator.PressAsync("Enter");
param: Locator.pressSequentially.text
Added in: v1.38
text<string>
String of characters to sequentially press into a focused element.
option: Locator.pressSequentially.delay
Added in: v1.38
delay<float>
Time to wait between key presses in milliseconds. Defaults to 0.
option: Locator.pressSequentially.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.38
option: Locator.pressSequentially.timeout = %%-input-timeout-%%
Added in: v1.38
option: Locator.pressSequentially.timeout = %%-input-timeout-js-%%
Added in: v1.38
async method: Locator.screenshot
Added in: v1.14 Returns:
Buffer
Take a screenshot of the element matching the locator.
Usage
await page.getByRole('link').screenshot();
page.getByRole(AriaRole.LINK).screenshot();
await page.get_by_role("link").screenshot()
page.get_by_role("link").screenshot()
await page.GetByRole(AriaRole.Link).ScreenshotAsync();
Disable animations and save screenshot to a file:
await page.getByRole('link').screenshot({ animations: 'disabled', path: 'link.png' });
page.getByRole(AriaRole.LINK).screenshot(new Locator.ScreenshotOptions()
.setAnimations(ScreenshotAnimations.DISABLED)
.setPath(Paths.get("example.png")));
await page.get_by_role("link").screenshot(animations="disabled", path="link.png")
page.get_by_role("link").screenshot(animations="disabled", path="link.png")
await page.GetByRole(AriaRole.Link).ScreenshotAsync(new() {
Animations = ScreenshotAnimations.Disabled,
Path = "link.png"
});
Details
This method captures a screenshot of the page, clipped to the size and position of a particular element matching the locator. If the element is covered by other elements, it will not be actually visible on the screenshot. If the element is a scrollable container, only the currently scrolled content will be visible on the 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.
Returns the buffer with the captured screenshot.
option: Locator.screenshot.-inline- = %%-screenshot-options-common-list-v1.8-%%
Added in: v1.14
option: Locator.screenshot.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.screenshot.timeout = %%-input-timeout-js-%%
Added in: v1.14
option: Locator.screenshot.maskColor = %%-screenshot-option-mask-color-%%
Added in: v1.34
option: Locator.screenshot.style = %%-screenshot-option-style-%%
Added in: v1.41
async method: Locator.scrollIntoViewIfNeeded
Added in: v1.14
This method waits for actionability checks, then tries to scroll element into view, unless it is
completely visible as defined by
IntersectionObserver's ratio.
See scrolling for alternative ways to scroll.
option: Locator.scrollIntoViewIfNeeded.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.scrollIntoViewIfNeeded.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.selectOption
Added in: v1.14 Returns:
Array<string>
Selects option or options in <select>.
Details
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.
Usage
<select multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
// single selection matching the value or label
element.selectOption('blue');
// single selection matching the label
element.selectOption({ label: 'Blue' });
// multiple selection for red, green and blue options
element.selectOption(['red', 'green', 'blue']);
// single selection matching the value or label
element.selectOption("blue");
// single selection matching the label
element.selectOption(new SelectOption().setLabel("Blue"));
// multiple selection for blue, red and second option
element.selectOption(new String[] {"red", "green", "blue"});
# single selection matching the value or label
await element.select_option("blue")
# single selection matching the label
await element.select_option(label="blue")
# multiple selection for blue, red and second option
await element.select_option(value=["red", "green", "blue"])
# single selection matching the value or label
element.select_option("blue")
# single selection matching the label
element.select_option(label="blue")
# multiple selection for blue, red and second option
element.select_option(value=["red", "green", "blue"])
// single selection matching the value or label
await element.SelectOptionAsync(new[] { "blue" });
// single selection matching the label
await element.SelectOptionAsync(new[] { new SelectOptionValue() { Label = "blue" } });
// multiple selection for blue, red and second option
await element.SelectOptionAsync(new[] { "red", "green", "blue" });
param: Locator.selectOption.values = %%-select-options-values-%%
Added in: v1.14
option: Locator.selectOption.force = %%-input-force-%%
Added in: v1.14
option: Locator.selectOption.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.selectOption.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.selectOption.timeout = %%-input-timeout-js-%%
Added in: v1.14
param: Locator.selectOption.element = %%-python-select-options-element-%%
Added in: v1.14
param: Locator.selectOption.index = %%-python-select-options-index-%%
Added in: v1.14
param: Locator.selectOption.value = %%-python-select-options-value-%%
Added in: v1.14
param: Locator.selectOption.label = %%-python-select-options-label-%%
Added in: v1.14
async method: Locator.selectText
Added in: v1.14
This method waits for actionability checks, then focuses the element and selects all its text content.
If the element is inside the <label> element that has an associated control, focuses and selects text in the control instead.
option: Locator.selectText.force = %%-input-force-%%
Added in: v1.14
option: Locator.selectText.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.selectText.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.setChecked
Added in: v1.15
Set the state of a checkbox or a radio element.
Usage
await page.getByRole('checkbox').setChecked(true);
page.getByRole(AriaRole.CHECKBOX).setChecked(true);
await page.get_by_role("checkbox").set_checked(True)
page.get_by_role("checkbox").set_checked(True)
await page.GetByRole(AriaRole.Checkbox).SetCheckedAsync(true);
Details
This method checks or unchecks an element by performing the following steps:
- Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- If the element already has the right checked state, this method returns immediately.
- 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 Page.mouse to click in the center of the element.
- Ensure that the element is now checked or unchecked. If not, this method throws.
When all steps combined have not finished during the specified timeout, this method throws a
TimeoutError. Passing zero timeout disables this.
param: Locator.setChecked.checked = %%-input-checked-%%
Added in: v1.15
option: Locator.setChecked.force = %%-input-force-%%
Added in: v1.15
option: Locator.setChecked.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.15
option: Locator.setChecked.position = %%-input-position-%%
Added in: v1.15
option: Locator.setChecked.timeout = %%-input-timeout-%%
Added in: v1.15
option: Locator.setChecked.timeout = %%-input-timeout-js-%%
Added in: v1.15
option: Locator.setChecked.trial = %%-input-trial-%%
Added in: v1.15
async method: Locator.setInputFiles
Added in: v1.14
Upload file or multiple files into <input type=file>.
For inputs with a [webkitdirectory] attribute, only a single directory path is supported.
Usage
// Select one file
await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));
// Select multiple files
await page.getByLabel('Upload files').setInputFiles([
path.join(__dirname, 'file1.txt'),
path.join(__dirname, 'file2.txt'),
]);
// Select a directory
await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir'));
// Remove all the selected files
await page.getByLabel('Upload file').setInputFiles([]);
// Upload buffer from memory
await page.getByLabel('Upload file').setInputFiles({
name: 'file.txt',
mimeType: 'text/plain',
buffer: Buffer.from('this is test')
});
// Select one file
page.getByLabel("Upload file").setInputFiles(Paths.get("myfile.pdf"));
// Select multiple files
page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
// Select a directory
page.getByLabel("Upload directory").setInputFiles(Paths.get("mydir"));
// Remove all the selected files
page.getByLabel("Upload file").setInputFiles(new Path[0]);
// Upload buffer from memory
page.getByLabel("Upload file").setInputFiles(new FilePayload(
"file.txt", "text/plain", "this is test".getBytes(StandardCharsets.UTF_8)));
# Select one file
await page.get_by_label("Upload file").set_input_files('myfile.pdf')
# Select multiple files
await page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
# Select a directory
await page.get_by_label("Upload directory").set_input_files('mydir')
# Remove all the selected files
await page.get_by_label("Upload file").set_input_files([])
# Upload buffer from memory
await page.get_by_label("Upload file").set_input_files(
files=[
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
],
)
# Select one file
page.get_by_label("Upload file").set_input_files('myfile.pdf')
# Select multiple files
page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
# Select a directory
page.get_by_label("Upload directory").set_input_files('mydir')
# Remove all the selected files
page.get_by_label("Upload file").set_input_files([])
# Upload buffer from memory
page.get_by_label("Upload file").set_input_files(
files=[
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
],
)
// Select one file
await page.GetByLabel("Upload file").SetInputFilesAsync("myfile.pdf");
// Select multiple files
await page.GetByLabel("Upload files").SetInputFilesAsync(new[] { "file1.txt", "file12.txt" });
// Select a directory
await page.GetByLabel("Upload directory").SetInputFilesAsync("mydir");
// Remove all the selected files
await page.GetByLabel("Upload file").SetInputFilesAsync(new[] {});
// Upload buffer from memory
await page.GetByLabel("Upload file").SetInputFilesAsync(new FilePayload
{
Name = "file.txt",
MimeType = "text/plain",
Buffer = System.Text.Encoding.UTF8.GetBytes("this is a test"),
});
Details
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 current working directory. For empty array, clears the selected files.
This method expects Locator to point to an
input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.
param: Locator.setInputFiles.files = %%-input-files-%%
Added in: v1.14
option: Locator.setInputFiles.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.setInputFiles.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.setInputFiles.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.tap
Added in: v1.14
Perform a tap gesture on the element matching the locator. For examples of emulating other gestures by manually dispatching touch events, see the emulating legacy touch events page.
Details
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 Page.touchscreen to tap the center of the element, or the specified position.
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.
element.tap() requires that the hasTouch option of the browser context be set to true.
option: Locator.tap.position = %%-input-position-%%
Added in: v1.14
option: Locator.tap.modifiers = %%-input-modifiers-%%
Added in: v1.14
option: Locator.tap.force = %%-input-force-%%
Added in: v1.14
option: Locator.tap.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.tap.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.tap.timeout = %%-input-timeout-js-%%
Added in: v1.14
option: Locator.tap.trial = %%-input-trial-with-modifiers-%%
Added in: v1.14
async method: Locator.textContent
Added in: v1.14 Returns:
null|string
Returns the node.textContent.
If you need to assert text on the page, prefer LocatorAssertions.toHaveText() to avoid flakiness. See assertions guide for more details.
option: Locator.textContent.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.textContent.timeout = %%-input-timeout-js-%%
Added in: v1.14
method: Locator.toString
Added in: v1.57
Languages: JavaScript Returns:
string
Returns a human-readable representation of the locator, using the Locator.description() if one exists; otherwise, it generates a string based on the locator's selector.
async method: Locator.type
Added in: v1.14
⚠️ Deprecated. In most cases, you should use Locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use Locator.pressSequentially().
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 Locator.press().
Usage
param: Locator.type.text
Added in: v1.14
text<string>
A text to type into a focused element.
option: Locator.type.delay
Added in: v1.14
delay<float>
Time to wait between key presses in milliseconds. Defaults to 0.
option: Locator.type.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.type.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.type.timeout = %%-input-timeout-js-%%
Added in: v1.14
async method: Locator.uncheck
Added in: v1.14
Ensure that checkbox or radio element is unchecked.
Usage
await page.getByRole('checkbox').uncheck();
page.getByRole(AriaRole.CHECKBOX).uncheck();
await page.get_by_role("checkbox").uncheck()
page.get_by_role("checkbox").uncheck()
await page.GetByRole(AriaRole.Checkbox).UncheckAsync();
Details
This method unchecks 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 Page.mouse to click in the center of the element.
- 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.
option: Locator.uncheck.position = %%-input-position-%%
Added in: v1.14
option: Locator.uncheck.force = %%-input-force-%%
Added in: v1.14
option: Locator.uncheck.noWaitAfter = %%-input-no-wait-after-removed-%%
Added in: v1.14
option: Locator.uncheck.timeout = %%-input-timeout-%%
Added in: v1.14
option: Locator.uncheck.timeout = %%-input-timeout-js-%%
Added in: v1.14
option: Locator.uncheck.trial = %%-input-trial-%%
Added in: v1.14
async method: Locator.waitFor
Added in: v1.16
Returns when element specified by locator satisfies the state option.
If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to timeout milliseconds until the condition is met.
Usage
const orderSent = page.locator('#order-sent');
await orderSent.waitFor();
Locator orderSent = page.locator("#order-sent");
orderSent.waitFor();
order_sent = page.locator("#order-sent")
await order_sent.wait_for()
order_sent = page.locator("#order-sent")
order_sent.wait_for()
var orderSent = page.Locator("#order-sent");
orderSent.WaitForAsync();
option: Locator.waitFor.state = %%-wait-for-selector-state-%%
Added in: v1.16
option: Locator.waitFor.timeout = %%-input-timeout-%%
Added in: v1.16
option: Locator.waitFor.timeout = %%-input-timeout-js-%%
Added in: v1.16