Playwright文档 - Locator(定位器)


定位器是 Playwright 自动等待和重试能力的核心部分。简而言之,定位器代表了一种随时在页面上查找元素的方法。可以使用page.locator()方法创建定位器。

class: Locator

  • since: v1.14

Locators are the central piece of Playwright'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 [method: Page.locator] method.

Learn more about locators.

async method: Locator.all

  • since: 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.

:::note [method: 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, [method: 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 [method: Locator.all]. :::

Usage

1for (const li of await page.getByRole('listitem').all()) 2 await li.click(); 3
1for li in await page.get_by_role('listitem').all(): 2 await li.click(); 3
1for li in page.get_by_role('listitem').all(): 2 li.click(); 3
1for (Locator li : page.getByRole('listitem').all()) 2 li.click(); 3
1foreach (var li in await page.GetByRole("listitem").AllAsync()) 2 await li.ClickAsync(); 3

async method: Locator.allInnerTexts

  • since: v1.14
  • returns: <[Array]<[string]>>

Returns an array of node.innerText values for all matching nodes.

Usage

1const texts = await page.getByRole('link').allInnerTexts(); 2
1texts = await page.get_by_role("link").all_inner_texts() 2
1texts = page.get_by_role("link").all_inner_texts() 2
1String[] texts = page.getByRole(AriaRole.LINK).allInnerTexts(); 2
1var texts = await page.GetByRole(AriaRole.Link).AllInnerTextsAsync(); 2

async method: Locator.allTextContents

  • since: v1.14
  • returns: <[Array]<[string]>>

Returns an array of node.textContent values for all matching nodes.

Usage

1const texts = await page.getByRole('link').allTextContents(); 2
1texts = await page.get_by_role("link").all_text_contents() 2
1texts = page.get_by_role("link").all_text_contents() 2
1String[] texts = page.getByRole(AriaRole.LINK).allTextContents(); 2
1var texts = await page.GetByRole(AriaRole.Link).AllTextContentsAsync(); 2

method: Locator.and

  • since: v1.34
  • langs:
    • alias-python: and_
  • 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.

1const button = page.getByRole('button').and(page.getByTitle('Subscribe')); 2
1Locator button = page.getByRole(AriaRole.BUTTON).and(page.getByTitle("Subscribe")); 2
1button = page.get_by_role("button").and_(page.getByTitle("Subscribe")) 2
1button = page.get_by_role("button").and_(page.getByTitle("Subscribe")) 2
1var button = page.GetByRole(AriaRole.Button).And(page.GetByTitle("Subscribe")); 2

param: Locator.and.locator

  • since: v1.34
  • locator <[Locator]>

Additional locator to match.

async method: Locator.blur

  • since: v1.28

Calls blur on the element.

option: Locator.blur.timeout = %%-input-timeout-%%

  • since: v1.28

option: Locator.blur.timeout = %%-input-timeout-js-%%

  • since: v1.28

async method: Locator.boundingBox

  • since: 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

1const box = await page.getByRole('button').boundingBox(); 2await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); 3
1BoundingBox box = page.getByRole(AriaRole.BUTTON).boundingBox(); 2page.mouse().click(box.x + box.width / 2, box.y + box.height / 2); 3
1box = await page.get_by_role("button").bounding_box() 2await page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) 3
1box = page.get_by_role("button").bounding_box() 2page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) 3
1var box = await page.GetByRole(AriaRole.Button).BoundingBoxAsync(); 2await page.Mouse.ClickAsync(box.X + box.Width / 2, box.Y + box.Height / 2); 3

option: Locator.boundingBox.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.boundingBox.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.check

  • since: v1.14

Ensure that checkbox or radio element is checked.

Details

Performs the following steps:

  1. 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.
  2. Wait for actionability checks on the element, unless [option: force] option is set.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element.
  5. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  6. 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 [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

Usage

1await page.getByRole('checkbox').check(); 2
1page.getByRole(AriaRole.CHECKBOX).check(); 2
1await page.get_by_role("checkbox").check() 2
1page.get_by_role("checkbox").check() 2
1await page.GetByRole(AriaRole.Checkbox).CheckAsync(); 2

option: Locator.check.position = %%-input-position-%%

  • since: v1.14

option: Locator.check.force = %%-input-force-%%

  • since: v1.14

option: Locator.check.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.check.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.check.timeout = %%-input-timeout-js-%%

  • since: v1.14

option: Locator.check.trial = %%-input-trial-%%

  • since: v1.14

async method: Locator.clear

  • since: 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

1await page.getByRole('textbox').clear(); 2
1page.getByRole(AriaRole.TEXTBOX).clear(); 2
1await page.get_by_role("textbox").clear() 2
1page.get_by_role("textbox").clear() 2
1await page.GetByRole(AriaRole.Textbox).ClearAsync(); 2

option: Locator.clear.force = %%-input-force-%%

  • since: v1.28

option: Locator.clear.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.28

option: Locator.clear.timeout = %%-input-timeout-%%

  • since: v1.28

option: Locator.clear.timeout = %%-input-timeout-js-%%

  • since: v1.28

async method: Locator.click

  • since: v1.14

Click an element.

Details

This method clicks the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.mouse] to click in the center of the element, or the specified [option: position].
  4. Wait for initiated navigations to either succeed or fail, unless [option: 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 [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

Usage

Click a button:

1await page.getByRole('button').click(); 2
1page.getByRole(AriaRole.BUTTON).click(); 2
1await page.get_by_role("button").click() 2
1page.get_by_role("button").click() 2
1await page.GetByRole(AriaRole.Button).ClickAsync(); 2

Shift-right-click at a specific position on a canvas:

1await page.locator('canvas').click({ 2 button: 'right', 3 modifiers: ['Shift'], 4 position: { x: 23, y: 32 }, 5}); 6
1page.locator("canvas").click(new Locator.ClickOptions() 2 .setButton(MouseButton.RIGHT) 3 .setModifiers(Arrays.asList(KeyboardModifier.SHIFT)) 4 .setPosition(23, 32)); 5
1await page.locator("canvas").click( 2 button="right", modifiers=["Shift"], position={"x": 23, "y": 32} 3) 4
1page.locator("canvas").click( 2 button="right", modifiers=["Shift"], position={"x": 23, "y": 32} 3) 4
1await page.Locator("canvas").ClickAsync(new() { 2 Button = MouseButton.Right, 3 Modifiers = new[] { KeyboardModifier.Shift }, 4 Position = new Position { X = 0, Y = 0 } 5}); 6

option: Locator.click.button = %%-input-button-%%

  • since: v1.14

option: Locator.click.clickCount = %%-input-click-count-%%

  • since: v1.14

option: Locator.click.delay = %%-input-down-up-delay-%%

  • since: v1.14

option: Locator.click.position = %%-input-position-%%

  • since: v1.14

option: Locator.click.modifiers = %%-input-modifiers-%%

  • since: v1.14

option: Locator.click.force = %%-input-force-%%

  • since: v1.14

option: Locator.click.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.click.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.click.timeout = %%-input-timeout-js-%%

  • since: v1.14

option: Locator.click.trial = %%-input-trial-%%

  • since: v1.14

async method: Locator.count

  • since: v1.14
  • returns: <[int]>

Returns the number of elements matching the locator.

Usage

1const count = await page.getByRole('listitem').count(); 2
1count = await page.get_by_role("listitem").count() 2
1count = page.get_by_role("listitem").count() 2
1int count = page.getByRole(AriaRole.LISTITEM).count(); 2
1int count = await page.GetByRole(AriaRole.Listitem).CountAsync(); 2

async method: Locator.dblclick

  • since: v1.14
  • langs:
    • alias-csharp: DblClickAsync

Double-click an element.

Details

This method double clicks the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.mouse] to double click in the center of the element, or the specified [option: position].
  4. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set. Note that if the first click of the dblclick() triggers a navigation event, this method will throw.

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 [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

:::note element.dblclick() dispatches two click events and a single dblclick event. :::

option: Locator.dblclick.button = %%-input-button-%%

  • since: v1.14

option: Locator.dblclick.delay = %%-input-down-up-delay-%%

  • since: v1.14

option: Locator.dblclick.position = %%-input-position-%%

  • since: v1.14

option: Locator.dblclick.modifiers = %%-input-modifiers-%%

  • since: v1.14

option: Locator.dblclick.force = %%-input-force-%%

  • since: v1.14

option: Locator.dblclick.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.dblclick.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.dblclick.timeout = %%-input-timeout-js-%%

  • since: v1.14

option: Locator.dblclick.trial = %%-input-trial-%%

  • since: v1.14

async method: Locator.dispatchEvent

  • since: v1.14

Programmatically dispatch an event on the matching element.

Usage

1await locator.dispatchEvent('click'); 2
1locator.dispatchEvent("click"); 2
1await locator.dispatch_event("click") 2
1locator.dispatch_event("click") 2
1await locator.DispatchEventAsync("click"); 2

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 [param: type], initializes it with [param: eventInit] properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

Since [param: eventInit] is event-specific, please refer to the events documentation for the lists of initial properties:

You can also specify [JSHandle] as the property value if you want live objects to be passed into the event:

1// Note you can only create DataTransfer in Chromium and Firefox 2const dataTransfer = await page.evaluateHandle(() => new DataTransfer()); 3await locator.dispatchEvent('dragstart', { dataTransfer }); 4
1// Note you can only create DataTransfer in Chromium and Firefox 2JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()"); 3Map<String, Object> arg = new HashMap<>(); 4arg.put("dataTransfer", dataTransfer); 5locator.dispatchEvent("dragstart", arg); 6
1# note you can only create data_transfer in chromium and firefox 2data_transfer = await page.evaluate_handle("new DataTransfer()") 3await locator.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer}) 4
1# note you can only create data_transfer in chromium and firefox 2data_transfer = page.evaluate_handle("new DataTransfer()") 3locator.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer}) 4
1var dataTransfer = await page.EvaluateHandleAsync("() => new DataTransfer()"); 2await locator.DispatchEventAsync("dragstart", new Dictionary<string, object> 3{ 4 { "dataTransfer", dataTransfer } 5}); 6

param: Locator.dispatchEvent.type

  • since: v1.14
  • type <[string]>

DOM event type: "click", "dragstart", etc.

param: Locator.dispatchEvent.eventInit

  • since: v1.14
  • eventInit ?<[EvaluationArgument]>

Optional event-specific initialization properties.

option: Locator.dispatchEvent.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.dispatchEvent.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.dragTo

  • since: 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

1const source = page.locator('#source'); 2const target = page.locator('#target'); 3 4await source.dragTo(target); 5// or specify exact positions relative to the top-left corners of the elements: 6await source.dragTo(target, { 7 sourcePosition: { x: 34, y: 7 }, 8 targetPosition: { x: 10, y: 20 }, 9}); 10
1Locator source = page.locator("#source"); 2Locator target = page.locator("#target"); 3 4source.dragTo(target); 5// or specify exact positions relative to the top-left corners of the elements: 6source.dragTo(target, new Locator.DragToOptions() 7 .setSourcePosition(34, 7).setTargetPosition(10, 20)); 8
1source = page.locator("#source") 2target = page.locator("#target") 3 4await source.drag_to(target) 5# or specify exact positions relative to the top-left corners of the elements: 6await source.drag_to( 7 target, 8 source_position={"x": 34, "y": 7}, 9 target_position={"x": 10, "y": 20} 10) 11
1source = page.locator("#source") 2target = page.locator("#target") 3 4source.drag_to(target) 5# or specify exact positions relative to the top-left corners of the elements: 6source.drag_to( 7 target, 8 source_position={"x": 34, "y": 7}, 9 target_position={"x": 10, "y": 20} 10) 11
1var source = Page.Locator("#source"); 2var target = Page.Locator("#target"); 3 4await source.DragToAsync(target); 5// or specify exact positions relative to the top-left corners of the elements: 6await source.DragToAsync(target, new() 7{ 8 SourcePosition = new() { X = 34, Y = 7 }, 9 TargetPosition = new() { X = 10, Y = 20 }, 10}); 11

param: Locator.dragTo.target

  • since: v1.18
  • target <[Locator]>

Locator of the element to drag to.

option: Locator.dragTo.force = %%-input-force-%%

  • since: v1.18

option: Locator.dragTo.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.18

option: Locator.dragTo.timeout = %%-input-timeout-%%

  • since: v1.18

option: Locator.dragTo.timeout = %%-input-timeout-js-%%

  • since: v1.18

option: Locator.dragTo.trial = %%-input-trial-%%

  • since: v1.18

option: Locator.dragTo.sourcePosition = %%-input-source-position-%%

  • since: v1.18

option: Locator.dragTo.targetPosition = %%-input-target-position-%%

  • since: v1.18

async method: Locator.elementHandle

  • since: v1.14
  • discouraged: Always prefer using [Locator]s and web assertions over [ElementHandle]s 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-%%

  • since: v1.14

option: Locator.elementHandle.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.elementHandles

  • since: v1.14
  • discouraged: Always prefer using [Locator]s and web assertions over [ElementHandle]s 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.

async method: Locator.evaluate

  • since: v1.14
  • returns: <[Serializable]>

Execute JavaScript code in the page, taking the matching element as an argument.

Details

Returns the return value of [param: expression], called with the matching element as a first argument, and [param: arg] as a second argument.

If [param: expression] returns a [Promise], this method will wait for the promise to resolve and return its value.

If [param: expression] throws or rejects, this method throws.

Usage

1const tweets = page.locator('.tweet .retweets'); 2expect(await tweets.evaluate(node => node.innerText)).toBe('10 retweets'); 3
1Locator tweets = page.locator(".tweet .retweets"); 2assertEquals("10 retweets", tweets.evaluate("node => node.innerText")); 3
1tweets = page.locator(".tweet .retweets") 2assert await tweets.evaluate("node => node.innerText") == "10 retweets" 3
1tweets = page.locator(".tweet .retweets") 2assert tweets.evaluate("node => node.innerText") == "10 retweets" 3
1var tweets = page.Locator(".tweet .retweets"); 2Assert.AreEqual("10 retweets", await tweets.EvaluateAsync("node => node.innerText")); 3

param: Locator.evaluate.expression = %%-evaluate-expression-%%

  • since: v1.14

param: Locator.evaluate.expression = %%-js-evaluate-pagefunction-%%

  • since: v1.14

param: Locator.evaluate.arg

  • since: v1.14
  • arg ?<[EvaluationArgument]>

Optional argument to pass to [param: expression].

option: Locator.evaluate.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.evaluate.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.evaluateAll

  • since: v1.14
  • returns: <[Serializable]>

Execute JavaScript code in the page, taking all matching elements as an argument.

Details

Returns the return value of [param: expression], called with an array of all matching elements as a first argument, and [param: arg] as a second argument.

If [param: expression] returns a [Promise], this method will wait for the promise to resolve and return its value.

If [param: expression] throws or rejects, this method throws.

Usage

1const locator = page.locator('div'); 2const moreThanTen = await locator.evaluateAll((divs, min) => divs.length > min, 10); 3
1Locator locator = page.locator("div"); 2boolean moreThanTen = (boolean) locator.evaluateAll("(divs, min) => divs.length > min", 10); 3
1locator = page.locator("div") 2more_than_ten = await locator.evaluate_all("(divs, min) => divs.length > min", 10) 3
1locator = page.locator("div") 2more_than_ten = locator.evaluate_all("(divs, min) => divs.length > min", 10) 3
1var locator = page.Locator("div"); 2var moreThanTen = await locator.EvaluateAllAsync<bool>("(divs, min) => divs.length > min", 10); 3

param: Locator.evaluateAll.expression = %%-evaluate-expression-%%

  • since: v1.14

param: Locator.evaluateAll.expression = %%-js-evaluate-pagefunction-%%

  • since: v1.14

param: Locator.evaluateAll.arg

  • since: v1.14
  • arg ?<[EvaluationArgument]>

Optional argument to pass to [param: expression].

async method: Locator.evaluateHandle

  • since: 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 [param: expression] as a[JSHandle], called with the matching element as a first argument, and [param: arg] as a second argument.

The only difference between [method: Locator.evaluate] and [method: Locator.evaluateHandle] is that [method: Locator.evaluateHandle] returns [JSHandle].

If [param: expression] returns a [Promise], this method will wait for the promise to resolve and return its value.

If [param: expression] throws or rejects, this method throws.

See [method: Page.evaluateHandle] for more details.

param: Locator.evaluateHandle.expression = %%-evaluate-expression-%%

  • since: v1.14

param: Locator.evaluateHandle.expression = %%-js-evaluate-pagefunction-%%

  • since: v1.14

param: Locator.evaluateHandle.arg

  • since: v1.14
  • arg ?<[EvaluationArgument]>

Optional argument to pass to [param: expression].

option: Locator.evaluateHandle.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.evaluateHandle.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.fill

  • since: v1.14

Set a value to the input field.

Usage

1await page.getByRole('textbox').fill('example value'); 2
1page.getByRole(AriaRole.TEXTBOX).fill("example value"); 2
1await page.get_by_role("textbox").fill("example value") 2
1page.get_by_role("textbox").fill("example value") 2
1await page.GetByRole(AriaRole.Textbox).FillAsync("example value"); 2

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 [method: Locator.pressSequentially].

param: Locator.fill.value

  • since: v1.14
  • value <[string]>

Value to set for the <input>, <textarea> or [contenteditable] element.

option: Locator.fill.force = %%-input-force-%%

  • since: v1.14

option: Locator.fill.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.fill.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.fill.timeout = %%-input-timeout-js-%%

  • since: v1.14

method: Locator.filter

  • since: 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

1const rowLocator = page.locator('tr'); 2// ... 3await rowLocator 4 .filter({ hasText: 'text in column 1' }) 5 .filter({ has: page.getByRole('button', { name: 'column 2 button' }) }) 6 .screenshot(); 7
1Locator rowLocator = page.locator("tr"); 2// ... 3rowLocator 4 .filter(new Locator.FilterOptions().setHasText("text in column 1")) 5 .filter(new Locator.FilterOptions().setHas( 6 page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("column 2 button")) 7 )) 8 .screenshot(); 9
1row_locator = page.locator("tr") 2# ... 3await row_locator.filter(has_text="text in column 1").filter( 4 has=page.get_by_role("button", name="column 2 button") 5).screenshot() 6 7
1row_locator = page.locator("tr") 2# ... 3row_locator.filter(has_text="text in column 1").filter( 4 has=page.get_by_role("button", name="column 2 button") 5).screenshot() 6
1var rowLocator = page.Locator("tr"); 2// ... 3await rowLocator 4 .Filter(new() { HasText = "text in column 1" }) 5 .Filter(new() { 6 Has = page.GetByRole(AriaRole.Button, new() { Name = "column 2 button" } ) 7 }) 8 .ScreenshotAsync(); 9

option: Locator.filter.-inline- = %%-locator-options-list-v1.14-%%

  • since: v1.22

option: Locator.filter.hasNot = %%-locator-option-has-not-%%

  • since: v1.33

option: Locator.filter.hasNotText = %%-locator-option-has-not-text-%%

  • since: v1.33

method: Locator.first

  • since: v1.14
  • returns: <[Locator]>

Returns locator to the first matching element.

async method: Locator.focus

  • since: v1.14

Calls focus on the matching element.

option: Locator.focus.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.focus.timeout = %%-input-timeout-js-%%

  • since: v1.14

method: Locator.frameLocator

  • since: 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

1const locator = page.frameLocator('iframe').getByText('Submit'); 2await locator.click(); 3
1Locator locator = page.frameLocator("iframe").getByText("Submit"); 2locator.click(); 3
1locator = page.frame_locator("iframe").get_by_text("Submit") 2await locator.click() 3
1locator = page.frame_locator("iframe").get_by_text("Submit") 2locator.click() 3
1var locator = page.FrameLocator("iframe").GetByText("Submit"); 2await locator.ClickAsync(); 3

param: Locator.frameLocator.selector = %%-find-selector-%%

  • since: v1.17

async method: Locator.getAttribute

  • since: v1.14
  • returns: <[null]|[string]>

Returns the matching element's attribute value.

param: Locator.getAttribute.name

  • since: v1.14
  • name <[string]>

Attribute name to get the value for.

option: Locator.getAttribute.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.getAttribute.timeout = %%-input-timeout-js-%%

  • since: v1.14

method: Locator.getByAltText

  • since: 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

  • since: 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

  • since: 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

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-role-%%

param: Locator.getByRole.role = %%-locator-get-by-role-role-%%

option: Locator.getByRole.-inline- = %%-locator-get-by-role-option-list-v1.27-%%

  • since: v1.27

option: Locator.getByRole.exact = %%-locator-get-by-role-option-exact-%%

method: Locator.getByTestId

  • since: v1.27
  • returns: <[Locator]>

%%-template-locator-get-by-test-id-%%

param: Locator.getByTestId.testId = %%-locator-get-by-test-id-test-id-%%

  • since: v1.27

method: Locator.getByText

  • since: 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

  • since: 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

  • since: v1.20

Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses [method: Locator.highlight].

async method: Locator.hover

  • since: v1.14

Hover over the matching element.

Usage

1await page.getByRole('link').hover(); 2
1await page.get_by_role("link").hover() 2
1page.get_by_role("link").hover() 2
1page.getByRole(AriaRole.LINK).hover(); 2
1await page.GetByRole(AriaRole.Link).HoverAsync(); 2

Details

This method hovers over the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.mouse] to hover over the center of the element, or the specified [option: position].
  4. 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 [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

option: Locator.hover.position = %%-input-position-%%

  • since: v1.14

option: Locator.hover.modifiers = %%-input-modifiers-%%

  • since: v1.14

option: Locator.hover.force = %%-input-force-%%

  • since: v1.14

option: Locator.hover.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.hover.timeout = %%-input-timeout-js-%%

  • since: v1.14

option: Locator.hover.trial = %%-input-trial-%%

  • since: v1.14

option: Locator.hover.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.28

async method: Locator.innerHTML

  • since: v1.14
  • returns: <[string]>

Returns the element.innerHTML.

option: Locator.innerHTML.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.innerHTML.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.innerText

  • since: v1.14
  • returns: <[string]>

Returns the element.innerText.

option: Locator.innerText.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.innerText.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.inputValue

  • since: v1.14
  • returns: <[string]>

Returns the value for the matching <input> or <textarea> or <select> element.

Usage

1const value = await page.getByRole('textbox').inputValue(); 2
1value = await page.get_by_role("textbox").input_value() 2
1value = page.get_by_role("textbox").input_value() 2
1String value = page.getByRole(AriaRole.TEXTBOX).inputValue(); 2
1String value = await page.GetByRole(AriaRole.Textbox).InputValueAsync(); 2

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

  • since: v1.14

option: Locator.inputValue.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.isChecked

  • since: v1.14
  • returns: <[boolean]>

Returns whether the element is checked. Throws if the element is not a checkbox or radio input.

Usage

1const checked = await page.getByRole('checkbox').isChecked(); 2
1boolean checked = page.getByRole(AriaRole.CHECKBOX).isChecked(); 2
1checked = await page.get_by_role("checkbox").is_checked() 2
1checked = page.get_by_role("checkbox").is_checked() 2
1var isChecked = await page.GetByRole(AriaRole.Checkbox).IsCheckedAsync(); 2

option: Locator.isChecked.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.isChecked.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.isDisabled

  • since: v1.14
  • returns: <[boolean]>

Returns whether the element is disabled, the opposite of enabled.

Usage

1const disabled = await page.getByRole('button').isDisabled(); 2
1boolean disabled = page.getByRole(AriaRole.BUTTON).isDisabled(); 2
1disabled = await page.get_by_role("button").is_disabled() 2
1disabled = page.get_by_role("button").is_disabled() 2
1Boolean disabled = await page.GetByRole(AriaRole.Button).IsDisabledAsync(); 2

option: Locator.isDisabled.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.isDisabled.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.isEditable

  • since: v1.14
  • returns: <[boolean]>

Returns whether the element is editable.

Usage

1const editable = await page.getByRole('textbox').isEditable(); 2
1boolean editable = page.getByRole(AriaRole.TEXTBOX).isEditable(); 2
1editable = await page.get_by_role("textbox").is_editable() 2
1editable = page.get_by_role("textbox").is_editable() 2
1Boolean editable = await page.GetByRole(AriaRole.Textbox).IsEditableAsync(); 2

option: Locator.isEditable.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.isEditable.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.isEnabled

  • since: v1.14
  • returns: <[boolean]>

Returns whether the element is enabled.

Usage

1const enabled = await page.getByRole('button').isEnabled(); 2
1boolean enabled = page.getByRole(AriaRole.BUTTON).isEnabled(); 2
1enabled = await page.get_by_role("button").is_enabled() 2
1enabled = page.get_by_role("button").is_enabled() 2
1Boolean enabled = await page.GetByRole(AriaRole.Button).IsEnabledAsync(); 2

option: Locator.isEnabled.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.isEnabled.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.isHidden

  • since: v1.14
  • returns: <[boolean]>

Returns whether the element is hidden, the opposite of visible.

Usage

1const hidden = await page.getByRole('button').isHidden(); 2
1boolean hidden = page.getByRole(AriaRole.BUTTON).isHidden(); 2
1hidden = await page.get_by_role("button").is_hidden() 2
1hidden = page.get_by_role("button").is_hidden() 2
1Boolean hidden = await page.GetByRole(AriaRole.Button).IsHiddenAsync(); 2

option: Locator.isHidden.timeout

  • since: v1.14
  • deprecated: This option is ignored. [method: Locator.isHidden] does not wait for the element to become hidden and returns immediately.
  • timeout <[float]>

async method: Locator.isVisible

  • since: v1.14
  • returns: <[boolean]>

Returns whether the element is visible.

Usage

1const visible = await page.getByRole('button').isVisible(); 2
1boolean visible = page.getByRole(AriaRole.BUTTON).isVisible(); 2
1visible = await page.get_by_role("button").is_visible() 2
1visible = page.get_by_role("button").is_visible() 2
1Boolean visible = await page.GetByRole(AriaRole.Button).IsVisibleAsync(); 2

option: Locator.isVisible.timeout

  • since: v1.14
  • deprecated: This option is ignored. [method: Locator.isVisible] does not wait for the element to become visible and returns immediately.
  • timeout <[float]>

method: Locator.last

  • since: v1.14
  • returns: <[Locator]>

Returns locator to the last matching element.

Usage

1const banana = await page.getByRole('listitem').last(); 2
1banana = await page.get_by_role("listitem").last 2
1banana = page.get_by_role("listitem").last 2
1Locator banana = page.getByRole(AriaRole.LISTITEM).last(); 2
1var banana = await page.GetByRole(AriaRole.Listitem).Last(1); 2

method: Locator.locator

  • since: v1.14
  • returns: <[Locator]>

%%-template-locator-locator-%%

param: Locator.locator.selectorOrLocator = %%-find-selector-or-locator-%%

  • since: v1.14

option: Locator.locator.-inline- = %%-locator-options-list-v1.14-%%

  • since: v1.14

option: Locator.locator.hasNot = %%-locator-option-has-not-%%

  • since: v1.33

option: Locator.locator.hasNotText = %%-locator-option-has-not-text-%%

  • since: v1.33

method: Locator.nth

  • since: v1.14
  • returns: <[Locator]>

Returns locator to the n-th matching element. It's zero based, nth(0) selects the first element.

Usage

1const banana = await page.getByRole('listitem').nth(2); 2
1banana = await page.get_by_role("listitem").nth(2) 2
1banana = page.get_by_role("listitem").nth(2) 2
1Locator banana = page.getByRole(AriaRole.LISTITEM).nth(2); 2
1var banana = await page.GetByRole(AriaRole.Listitem).Nth(2); 2

param: Locator.nth.index

  • since: v1.14
  • index <[int]>

method: Locator.or

  • since: v1.33
  • langs:
    • alias-python: or_
  • returns: <[Locator]>

Creates a locator that matches either of the two locators.

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.

1const newEmail = page.getByRole('button', { name: 'New' }); 2const dialog = page.getByText('Confirm security settings'); 3await expect(newEmail.or(dialog)).toBeVisible(); 4if (await dialog.isVisible()) 5 await page.getByRole('button', { name: 'Dismiss' }).click(); 6await newEmail.click(); 7
1Locator newEmail = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("New")); 2Locator dialog = page.getByText("Confirm security settings"); 3assertThat(newEmail.or(dialog)).isVisible(); 4if (dialog.isVisible()) 5 page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Dismiss")).click(); 6newEmail.click(); 7
1new_email = page.get_by_role("button", name="New") 2dialog = page.get_by_text("Confirm security settings") 3await expect(new_email.or_(dialog)).to_be_visible() 4if (await dialog.is_visible()): 5 await page.get_by_role("button", name="Dismiss").click() 6await new_email.click() 7
1new_email = page.get_by_role("button", name="New") 2dialog = page.get_by_text("Confirm security settings") 3expect(new_email.or_(dialog)).to_be_visible() 4if (dialog.is_visible()): 5 page.get_by_role("button", name="Dismiss").click() 6new_email.click() 7
1var newEmail = page.GetByRole(AriaRole.Button, new() { Name = "New" }); 2var dialog = page.GetByText("Confirm security settings"); 3await Expect(newEmail.Or(dialog)).ToBeVisibleAsync(); 4if (await dialog.IsVisibleAsync()) 5 await page.GetByRole(AriaRole.Button, new() { Name = "Dismiss" }).ClickAsync(); 6await newEmail.ClickAsync(); 7

param: Locator.or.locator

  • since: v1.33
  • locator <[Locator]>

Alternative locator to match.

method: Locator.page

  • since: v1.19
  • returns: <[Page]>

A page this locator belongs to.

async method: Locator.press

  • since: v1.14

Focuses the matching element and presses a combination of the keys.

Usage

1await page.getByRole('textbox').press('Backspace'); 2
1page.getByRole(AriaRole.TEXTBOX).press("Backspace"); 2
1await page.get_by_role("textbox").press("Backspace") 2
1page.get_by_role("textbox").press("Backspace") 2
1await page.GetByRole(AriaRole.Textbox).PressAsync("Backspace"); 2

Details

Focuses the element, and then uses [method: Keyboard.down] and [method: Keyboard.up].

[param: key] can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the [param: 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.

Holding down Shift will type the text that corresponds to the [param: key] in the upper case.

If [param: 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" 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

  • since: v1.14
  • key <[string]>

Name of the key to press or a character to generate, such as ArrowLeft or a.

option: Locator.press.delay

  • since: v1.14
  • delay <[float]>

Time to wait between keydown and keyup in milliseconds. Defaults to 0.

option: Locator.press.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.press.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.press.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.pressSequentially

  • since: v1.38

:::tip In most cases, you should use [method: 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 [method: Locator.press].

Usage

1await locator.pressSequentially('Hello'); // Types instantly 2await locator.pressSequentially('World', { delay: 100 }); // Types slower, like a user 3
1locator.pressSequentially("Hello"); // Types instantly 2locator.pressSequentially("World", new Locator.pressSequentiallyOptions().setDelay(100)); // Types slower, like a user 3
1await locator.press_sequentially("hello") # types instantly 2await locator.press_sequentially("world", delay=100) # types slower, like a user 3
1locator.press_sequentially("hello") # types instantly 2locator.press_sequentially("world", delay=100) # types slower, like a user 3
1await locator.PressSequentiallyAsync("Hello"); // Types instantly 2await locator.PressSequentiallyAsync("World", new() { Delay = 100 }); // Types slower, like a user 3

An example of typing into a text field and then submitting the form:

1const locator = page.getByLabel('Password'); 2await locator.pressSequentially('my password'); 3await locator.press('Enter'); 4
1Locator locator = page.getByLabel("Password"); 2locator.pressSequentially("my password"); 3locator.press("Enter"); 4
1locator = page.get_by_label("Password") 2await locator.press_sequentially("my password") 3await locator.press("Enter") 4
1locator = page.get_by_label("Password") 2locator.press_sequentially("my password") 3locator.press("Enter") 4
1var locator = page.GetByLabel("Password"); 2await locator.PressSequentiallyAsync("my password"); 3await locator.PressAsync("Enter"); 4

param: Locator.pressSequentially.text

  • since: v1.38
  • text <[string]>

String of characters to sequentially press into a focused element.

option: Locator.pressSequentially.delay

  • since: v1.38
  • delay <[float]>

Time to wait between key presses in milliseconds. Defaults to 0.

option: Locator.pressSequentially.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.38

option: Locator.pressSequentially.timeout = %%-input-timeout-%%

  • since: v1.38

option: Locator.pressSequentially.timeout = %%-input-timeout-js-%%

  • since: v1.38

async method: Locator.screenshot

  • since: v1.14
  • returns: <[Buffer]>

Take a screenshot of the element matching the locator.

Usage

1await page.getByRole('link').screenshot(); 2
1page.getByRole(AriaRole.LINK).screenshot(); 2
1await page.get_by_role("link").screenshot() 2
1page.get_by_role("link").screenshot() 2
1await page.GetByRole(AriaRole.Link).ScreenshotAsync(); 2

Disable animations and save screenshot to a file:

1await page.getByRole('link').screenshot({ animations: 'disabled', path: 'link.png' }); 2
1page.getByRole(AriaRole.LINK).screenshot(new Locator.ScreenshotOptions() 2 .setAnimations(ScreenshotAnimations.DISABLED) 3 .setPath(Paths.get("example.png"))); 4
1await page.get_by_role("link").screenshot(animations="disabled", path="link.png") 2
1page.get_by_role("link").screenshot(animations="disabled", path="link.png") 2
1await page.GetByRole(AriaRole.Link).ScreenshotAsync(new() { 2 Animations = ScreenshotAnimations.Disabled, 3 Path = "link.png" 4}); 5

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

  • since: v1.14

option: Locator.screenshot.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.screenshot.timeout = %%-input-timeout-js-%%

  • since: v1.14

option: Locator.screenshot.maskColor = %%-screenshot-option-mask-color-%%

  • since: v1.34

async method: Locator.scrollIntoViewIfNeeded

  • since: 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.

option: Locator.scrollIntoViewIfNeeded.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.scrollIntoViewIfNeeded.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.selectOption

  • since: 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

1<select multiple> 2 <option value="red">Red</div> 3 <option value="green">Green</div> 4 <option value="blue">Blue</div> 5</select> 6
1// single selection matching the value or label 2element.selectOption('blue'); 3 4// single selection matching the label 5element.selectOption({ label: 'Blue' }); 6 7// multiple selection for red, green and blue options 8element.selectOption(['red', 'green', 'blue']); 9
1// single selection matching the value or label 2element.selectOption("blue"); 3// single selection matching the label 4element.selectOption(new SelectOption().setLabel("Blue")); 5// multiple selection for blue, red and second option 6element.selectOption(new String[] {"red", "green", "blue"}); 7
1# single selection matching the value or label 2await element.select_option("blue") 3# single selection matching the label 4await element.select_option(label="blue") 5# multiple selection for blue, red and second option 6await element.select_option(value=["red", "green", "blue"]) 7
1# single selection matching the value or label 2element.select_option("blue") 3# single selection matching the label 4element.select_option(label="blue") 5# multiple selection for blue, red and second option 6element.select_option(value=["red", "green", "blue"]) 7
1// single selection matching the value or label 2await element.SelectOptionAsync(new[] { "blue" }); 3// single selection matching the label 4await element.SelectOptionAsync(new[] { new SelectOptionValue() { Label = "blue" } }); 5// multiple selection for blue, red and second option 6await element.SelectOptionAsync(new[] { "red", "green", "blue" }); 7

param: Locator.selectOption.values = %%-select-options-values-%%

  • since: v1.14

option: Locator.selectOption.force = %%-input-force-%%

  • since: v1.14

option: Locator.selectOption.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.selectOption.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.selectOption.timeout = %%-input-timeout-js-%%

  • since: v1.14

param: Locator.selectOption.element = %%-python-select-options-element-%%

  • since: v1.14

param: Locator.selectOption.index = %%-python-select-options-index-%%

  • since: v1.14

param: Locator.selectOption.value = %%-python-select-options-value-%%

  • since: v1.14

param: Locator.selectOption.label = %%-python-select-options-label-%%

  • since: v1.14

async method: Locator.selectText

  • since: 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-%%

  • since: v1.14

option: Locator.selectText.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.selectText.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.setChecked

  • since: v1.15

Set the state of a checkbox or a radio element.

Usage

1await page.getByRole('checkbox').setChecked(true); 2
1page.getByRole(AriaRole.CHECKBOX).setChecked(true); 2
1await page.get_by_role("checkbox").set_checked(True) 2
1page.get_by_role("checkbox").set_checked(True) 2
1await page.GetByRole(AriaRole.Checkbox).SetCheckedAsync(true); 2

Details

This method checks or unchecks an element by performing the following steps:

  1. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
  2. If the element already has the right checked state, this method returns immediately.
  3. Wait for actionability checks on the matched element, unless [option: force] option is set. If the element is detached during the checks, the whole action is retried.
  4. Scroll the element into view if needed.
  5. Use [property: Page.mouse] to click in the center of the element.
  6. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  7. Ensure that the element is now checked or unchecked. If not, this method throws.

When all steps combined have not finished during the specified [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

param: Locator.setChecked.checked = %%-input-checked-%%

  • since: v1.15

option: Locator.setChecked.force = %%-input-force-%%

  • since: v1.15

option: Locator.setChecked.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.15

option: Locator.setChecked.position = %%-input-position-%%

  • since: v1.15

option: Locator.setChecked.timeout = %%-input-timeout-%%

  • since: v1.15

option: Locator.setChecked.timeout = %%-input-timeout-js-%%

  • since: v1.15

option: Locator.setChecked.trial = %%-input-trial-%%

  • since: v1.15

async method: Locator.setInputFiles

  • since: v1.14

Upload file or multiple files into <input type=file>.

Usage

1// Select one file 2await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf')); 3 4// Select multiple files 5await page.getByLabel('Upload files').setInputFiles([ 6 path.join(__dirname, 'file1.txt'), 7 path.join(__dirname, 'file2.txt'), 8]); 9 10// Remove all the selected files 11await page.getByLabel('Upload file').setInputFiles([]); 12 13// Upload buffer from memory 14await page.getByLabel('Upload file').setInputFiles({ 15 name: 'file.txt', 16 mimeType: 'text/plain', 17 buffer: Buffer.from('this is test') 18}); 19
1// Select one file 2page.getByLabel("Upload file").setInputFiles(Paths.get("myfile.pdf")); 3 4// Select multiple files 5page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")}); 6 7// Remove all the selected files 8page.getByLabel("Upload file").setInputFiles(new Path[0]); 9 10// Upload buffer from memory 11page.getByLabel("Upload file").setInputFiles(new FilePayload( 12 "file.txt", "text/plain", "this is test".getBytes(StandardCharsets.UTF_8))); 13
1# Select one file 2await page.get_by_label("Upload file").set_input_files('myfile.pdf') 3 4# Select multiple files 5await page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt']) 6 7# Remove all the selected files 8await page.get_by_label("Upload file").set_input_files([]) 9 10# Upload buffer from memory 11await page.get_by_label("Upload file").set_input_files( 12 files=[ 13 {"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"} 14 ], 15) 16
1# Select one file 2page.get_by_label("Upload file").set_input_files('myfile.pdf') 3 4# Select multiple files 5page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt']) 6 7# Remove all the selected files 8page.get_by_label("Upload file").set_input_files([]) 9 10# Upload buffer from memory 11page.get_by_label("Upload file").set_input_files( 12 files=[ 13 {"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"} 14 ], 15) 16
1// Select one file 2await page.GetByLabel("Upload file").SetInputFilesAsync("myfile.pdf"); 3 4// Select multiple files 5await page.GetByLabel("Upload files").SetInputFilesAsync(new[] { "file1.txt", "file12.txt" }); 6 7// Remove all the selected files 8await page.GetByLabel("Upload file").SetInputFilesAsync(new[] {}); 9 10// Upload buffer from memory 11await page.GetByLabel("Upload file").SetInputFilesAsync(new FilePayload 12{ 13 Name = "file.txt", 14 MimeType = "text/plain", 15 Buffer = System.Text.Encoding.UTF8.GetBytes("this is a test"), 16}); 17

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

  • since: v1.14

option: Locator.setInputFiles.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.setInputFiles.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.setInputFiles.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.tap

  • since: v1.14

Perform a tap gesture on the element matching the locator.

Details

This method taps the element by performing the following steps:

  1. Wait for actionability checks on the element, unless [option: force] option is set.
  2. Scroll the element into view if needed.
  3. Use [property: Page.touchscreen] to tap the center of the element, or the specified [option: position].
  4. Wait for initiated navigations to either succeed or fail, unless [option: 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 [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

:::note element.tap() requires that the hasTouch option of the browser context be set to true. :::

option: Locator.tap.position = %%-input-position-%%

  • since: v1.14

option: Locator.tap.modifiers = %%-input-modifiers-%%

  • since: v1.14

option: Locator.tap.force = %%-input-force-%%

  • since: v1.14

option: Locator.tap.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.tap.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.tap.timeout = %%-input-timeout-js-%%

  • since: v1.14

option: Locator.tap.trial = %%-input-trial-%%

  • since: v1.14

async method: Locator.textContent

  • since: v1.14
  • returns: <[null]|[string]>

Returns the node.textContent.

option: Locator.textContent.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.textContent.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.type

  • since: v1.14
  • deprecated: In most cases, you should use [method: 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 [method: 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 [method: Locator.press].

Usage

param: Locator.type.text

  • since: v1.14
  • text <[string]>

A text to type into a focused element.

option: Locator.type.delay

  • since: v1.14
  • delay <[float]>

Time to wait between key presses in milliseconds. Defaults to 0.

option: Locator.type.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.type.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.type.timeout = %%-input-timeout-js-%%

  • since: v1.14

async method: Locator.uncheck

  • since: v1.14

Ensure that checkbox or radio element is unchecked.

Usage

1await page.getByRole('checkbox').uncheck(); 2
1page.getByRole(AriaRole.CHECKBOX).uncheck(); 2
1await page.get_by_role("checkbox").uncheck() 2
1page.get_by_role("checkbox").uncheck() 2
1await page.GetByRole(AriaRole.Checkbox).UncheckAsync(); 2

Details

This method unchecks the element by performing the following steps:

  1. 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.
  2. Wait for actionability checks on the element, unless [option: force] option is set.
  3. Scroll the element into view if needed.
  4. Use [property: Page.mouse] to click in the center of the element.
  5. Wait for initiated navigations to either succeed or fail, unless [option: noWaitAfter] option is set.
  6. 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 [option: timeout], this method throws a [TimeoutError]. Passing zero timeout disables this.

option: Locator.uncheck.position = %%-input-position-%%

  • since: v1.14

option: Locator.uncheck.force = %%-input-force-%%

  • since: v1.14

option: Locator.uncheck.noWaitAfter = %%-input-no-wait-after-%%

  • since: v1.14

option: Locator.uncheck.timeout = %%-input-timeout-%%

  • since: v1.14

option: Locator.uncheck.timeout = %%-input-timeout-js-%%

  • since: v1.14

option: Locator.uncheck.trial = %%-input-trial-%%

  • since: v1.14

async method: Locator.waitFor

  • since: v1.16

Returns when element specified by locator satisfies the [option: state] option.

If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to [option: timeout] milliseconds until the condition is met.

Usage

1const orderSent = page.locator('#order-sent'); 2await orderSent.waitFor(); 3
1Locator orderSent = page.locator("#order-sent"); 2orderSent.waitFor(); 3
1order_sent = page.locator("#order-sent") 2await order_sent.wait_for() 3
1order_sent = page.locator("#order-sent") 2order_sent.wait_for() 3
1var orderSent = page.Locator("#order-sent"); 2orderSent.WaitForAsync(); 3

option: Locator.waitFor.state = %%-wait-for-selector-state-%%

  • since: v1.16

option: Locator.waitFor.timeout = %%-input-timeout-%%

  • since: v1.16

option: Locator.waitFor.timeout = %%-input-timeout-js-%%

  • since: v1.16