Locator
定位器是 Playwright 自动等待和重试功能的核心部分。简而言之,定位器表示在任何时刻查找页面上元素的方式。可以使用 Page.Locator() 方法创建定位器。
🌐 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 Page.Locator() method.
方法
🌐 Methods
AllAsync
Added in: v1.29当定位器指向元素列表时,这将返回一个定位器数组,指向它们各自的元素。
🌐 When the locator points to a list of elements, this returns an array of locators, pointing to their respective elements.
Locator.AllAsync() 不会等待元素匹配定位器,而是会立即返回页面上存在的任何内容。
当元素列表动态变化时,Locator.AllAsync() 会产生不可预测和不稳定的结果。
🌐 When the list of elements changes dynamically, Locator.AllAsync() will produce unpredictable and flaky results.
当元素列表稳定但动态加载时,请在调用 Locator.AllAsync() 之前等待完整列表加载完成。
🌐 When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before calling Locator.AllAsync().
用法
foreach (var li in await page.GetByRole("listitem").AllAsync())
await li.ClickAsync();
返回
AllInnerTextsAsync
Added in: v1.14返回所有匹配节点的 node.innerText 值数组。
🌐 Returns an array of node.innerText values for all matching nodes.
如果你需要断言页面上的文本,建议使用 Expect(Locator).ToHaveTextAsync() 并选择 UseInnerText 选项,以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert text on the page, prefer Expect(Locator).ToHaveTextAsync() with UseInnerText option to avoid flakiness. See assertions guide for more details. :::
用法
var texts = await page.GetByRole(AriaRole.Link).AllInnerTextsAsync();
返回
AllTextContentsAsync
Added in: v1.14返回所有匹配节点的 node.textContent 值数组。
🌐 Returns an array of node.textContent values for all matching nodes.
如果你需要断言页面上的文本,建议使用 Expect(Locator).ToHaveTextAsync() 来避免测试不稳定。更多详情请参见 断言指南。
🌐 If you need to assert text on the page, prefer Expect(Locator).ToHaveTextAsync() to avoid flakiness. See assertions guide for more details. :::
用法
var texts = await page.GetByRole(AriaRole.Link).AllTextContentsAsync();
返回
And
Added in: v1.34创建一个与此定位器和参数定位器相匹配的定位器。
🌐 Creates a locator that matches both this locator and the argument locator.
用法
以下示例查找具有特定标题的按钮。
🌐 The following example finds a button with a specific title.
var button = page.GetByRole(AriaRole.Button).And(page.GetByTitle("Subscribe"));
参数
返回
AriaSnapshotAsync
Added in: v1.49捕获给定元素的 aria 快照。有关 aria 快照 和对应断言的 Expect(Locator).ToMatchAriaSnapshotAsync() 的更多信息,请参阅相关内容。
🌐 Captures the aria snapshot of the given element. Read more about aria snapshots and Expect(Locator).ToMatchAriaSnapshotAsync() for the corresponding assertion.
用法
await page.GetByRole(AriaRole.Link).AriaSnapshotAsync();
参数
optionsLocatorAriaSnapshotOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
此方法捕获给定元素的 aria 快照。快照是表示该元素及其子元素状态的字符串。快照可用于在测试中断言元素的状态,或与未来的状态进行比较。
🌐 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.
ARIA 快照使用 YAML 标记语言表示:
🌐 The ARIA snapshot is represented using YAML markup language:
- 对象的键是元素的角色和可选的可访问名称。
- 值是文本内容或子元素数组。
- 通用静态文本可以用
text键表示。
以下是 HTML 标记和相应的 ARIA 快照:
🌐 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"
BlurAsync
Added in: v1.28在该元素上调用 blur 方法。
🌐 Calls blur on the element.
用法
await Locator.BlurAsync(options);
参数
optionsLocatorBlurOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
BoundingBoxAsync
Added in: v1.14该方法返回与定位符匹配元素的边界框,若元素不可见则返回“null”。边界框是相对于主帧视口计算的——主帧视口通常和浏览器窗口相同。
🌐 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.
用法
var box = await page.GetByRole(AriaRole.Button).BoundingBoxAsync();
await page.Mouse.ClickAsync(box.X + box.Width / 2, box.Y + box.Height / 2);
参数
optionsLocatorBoundingBoxOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
- 边界框?#
-
x[float]元素的 x 坐标(以像素为单位)。
-
y[float]元素的 y 坐标(以像素为单位)。
-
width[float]元素的宽度(以像素为单位)。
-
height[float]元素的高度(以像素为单位)。
-
详情
滚动会影响返回的边界框,这与 Element.getBoundingClientRect 类似。这意味着 x 和/或 y 可能为负。
🌐 Scrolling affects the returned bounding box, similarly to Element.getBoundingClientRect. That means x and/or y may be negative.
来自子框架的元素返回相对于主框架的边界框,而不像 Element.getBoundingClientRect 那样。
🌐 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.
CheckAsync
Added in: v1.14确保复选框或单选元素已选中。
🌐 Ensure that checkbox or radio element is checked.
用法
await page.GetByRole(AriaRole.Checkbox).CheckAsync();
参数
optionsLocatorCheckOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
PositionPosition? (optional)#-
X[float] -
Y[float]
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
-
返回
详情
执行以下步骤:
🌐 Performs the following steps:
- 确保该元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经被选中,该方法会立即返回。
- 等待对该元素的可操作性检查,除非设置了强制选项。
- 如果需要,将元素滚动到视图中。
- 使用 Page.Mouse 点击元素的中心。
- 确保该元素现在已被选中。如果没有,该方法会抛出异常。
如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。
🌐 If the element is detached from the DOM at any moment during the action, this method throws.
当所有步骤在指定的 Timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
ClearAsync
Added in: v1.28清除输入字段。
🌐 Clear the input field.
用法
await page.GetByRole(AriaRole.Textbox).ClearAsync();
参数
optionsLocatorClearOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
此方法会等待 actionability 检查,聚焦该元素,清空它,并在清空后触发 input 事件。
🌐 This method waits for actionability checks, focuses the element, clears it and triggers an input event after clearing.
如果目标元素不是 <input>、<textarea> 或 [contenteditable] 元素,该方法会抛出错误。不过,如果该元素位于具有关联 控件 的 <label> 元素内,则会清除控件。
🌐 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.
ClickAsync
Added in: v1.14单击一个元素。
🌐 Click an element.
用法
单击一个按钮:
🌐 Click a button:
await page.GetByRole(AriaRole.Button).ClickAsync();
按住 Shift 键并右键单击画布上的特定位置:
🌐 Shift-right-click at a specific position on a canvas:
await page.Locator("canvas").ClickAsync(new() {
Button = MouseButton.Right,
Modifiers = new[] { KeyboardModifier.Shift },
Position = new Position { X = 0, Y = 0 }
});
参数
optionsLocatorClickOptions?(optional)-
Buttonenum MouseButton { Left, Right, Middle }?(optional)#默认为
left。 -
默认为 1。请参阅 UIEvent.detail。
-
Delay[float]? (optional)#mousedown和mouseup之间的等待时间,以毫秒为单位。默认值为 0。 -
是否绕过 可操作性 检查。默认值为
false。 -
ModifiersIEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
已弃用
该选项将来默认值为
true。发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为
false。 -
PositionPosition? (optional)#-
X[float] -
Y[float]
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
-
Stepsint? (optional) Added in: v1.57#默认为1。发送
n个插值的mousemove事件,以表示从 Playwright 当前光标位置到指定目的地的移动。当设置为1时,在目标位置只发出一个mousemove事件。 -
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
-
返回
详情
此方法通过执行以下步骤来单击元素:
🌐 This method clicks the element by performing the following steps:
- 等待对该元素的可操作性检查,除非设置了强制选项。
- 如果需要,将元素滚动到视图中。
- 使用 Page.Mouse 点击元素中心,或指定的 Position 位置。
- 等待已启动的导航要么成功,要么失败,除非设置了 NoWaitAfter 选项。
如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。
🌐 If the element is detached from the DOM at any moment during the action, this method throws.
当所有步骤在指定的 Timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
ContentFrame
Added in: v1.43返回一个 FrameLocator 对象,该对象指向与此定位器相同的 iframe。
🌐 Returns a FrameLocator object pointing to the same iframe as this locator.
当你从某处获得一个 Locator 对象,并且之后想与框架内的内容进行交互时,这很有用。
🌐 Useful when you have a Locator object obtained somewhere, and later on would like to interact with the content inside the frame.
对于反向操作,请使用 FrameLocator.Owner。
🌐 For a reverse operation, use FrameLocator.Owner.
用法
var locator = Page.Locator("iframe[name=\"embedded\"]");
// ...
var frameLocator = locator.ContentFrame;
await frameLocator.GetByRole(AriaRole.Button).ClickAsync();
返回
CountAsync
Added in: v1.14返回与定位器匹配的元素数。
🌐 Returns the number of elements matching the locator.
如果你需要断言页面上的元素数量,建议使用 Expect(Locator).ToHaveCountAsync() 以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert the number of elements on the page, prefer Expect(Locator).ToHaveCountAsync() to avoid flakiness. See assertions guide for more details. :::
用法
int count = await page.GetByRole(AriaRole.Listitem).CountAsync();
返回
DblClickAsync
Added in: v1.14双击一个元素。
🌐 Double-click an element.
用法
await Locator.DblClickAsync(options);
参数
optionsLocatorDblClickOptions?(optional)-
Buttonenum MouseButton { Left, Right, Middle }?(optional)#默认为
left。 -
Delay[float]? (optional)#mousedown和mouseup之间的等待时间,以毫秒为单位。默认值为 0。 -
是否绕过 可操作性 检查。默认值为
false。 -
ModifiersIEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
PositionPosition? (optional)#-
X[float] -
Y[float]
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
-
Stepsint? (optional) Added in: v1.57#默认为1。发送
n个插值的mousemove事件,以表示从 Playwright 当前光标位置到指定目的地的移动。当设置为1时,在目标位置只发出一个mousemove事件。 -
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
-
返回
详情
此方法通过执行以下步骤双击该元素:
🌐 This method double clicks the element by performing the following steps:
- 等待对该元素的可操作性检查,除非设置了强制选项。
- 如果需要,将元素滚动到视图中。
- 使用 Page.Mouse 在元素中心或指定的 Position 双击。
如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。
🌐 If the element is detached from the DOM at any moment during the action, this method throws.
当所有步骤在指定的 Timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
element.dblclick() 触发两个 click 事件和一个 dblclick 事件。
Describe
Added in: v1.53描述定位器,描述用于跟踪查看器和报告中。返回指向同一元素的定位器。
🌐 Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the same element.
用法
var button = Page.GetByTestId("btn-sub").Describe("Subscribe button");
await button.ClickAsync();
参数
返回
Description
Added in: v1.57返回之前使用 Locator.Describe() 设置的定位器描述。如果没有设置自定义描述,则返回 null。
🌐 Returns locator description previously set with Locator.Describe(). Returns null if no custom description has been set.
用法
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
返回
DispatchEventAsync
Added in: v1.14以编程方式在匹配元素上调度事件。
🌐 Programmatically dispatch an event on the matching element.
用法
await locator.DispatchEventAsync("click");
参数
-
DOM 事件类型:
"click"、"dragstart"等 -
eventInitEvaluationArgument? (optional)#可选的特定于事件的初始化属性。
-
optionsLocatorDispatchEventOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
上面的代码片段会在该元素上触发 click 事件。无论元素的可见状态如何,都会触发 click。这相当于调用 element.click()。
🌐 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().
在底层,它会根据给定的 type 创建一个事件实例,使用 eventInit 属性初始化它,并在元素上派发该事件。事件类型是 composed、cancelable,默认情况下会冒泡。
🌐 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.
由于 eventInit 是特定于事件的,请查阅事件文档以获取初始属性列表:
🌐 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
如果你希望将实时对象传递到事件中,你也可以将 JSHandle 指定为属性值:
🌐 You can also specify JSHandle as the property value if you want live objects to be passed into the event:
var dataTransfer = await page.EvaluateHandleAsync("() => new DataTransfer()");
await locator.DispatchEventAsync("dragstart", new Dictionary<string, object>
{
{ "dataTransfer", dataTransfer }
});
DragToAsync
Added in: v1.18将源元素拖向目标元素并将其放下。
🌐 Drag the source element towards the target element and drop it.
用法
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 },
});
参数
此选项无效。
-
SourcePositionSourcePosition? (optional)#-
X[float] -
Y[float]
在此位置点击源元素,相对于元素内边距框的左上角。如果未指定,则使用元素的某个可见点。
-
-
Stepsint? (optional) Added in: v1.57#默认为 1。发送
n个插值的mousemove事件以表示拖动的mousedown和mouseup之间的移动。当设置为 1 时,在目标位置仅触发一个mousemove事件。 -
TargetPositionTargetPosition? (optional)#-
X[float] -
Y[float]
在此点相对于元素填充框左上角投放目标元素。如果未指定,则使用元素的某个可见点。
-
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
返回
详情
此方法将定位器拖动到另一个目标定位器或目标位置。它将首先移动到源元素,执行 mousedown,然后移动到目标元素或位置并执行 mouseup。
🌐 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.
EvaluateAsync
Added in: v1.14在页面中执行 JavaScript 代码,将匹配元素作为参数。
🌐 Execute JavaScript code in the page, taking the matching element as an argument.
用法
将参数传递给 expression :
🌐 Passing argument to expression:
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"
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument? (optional)#可选参数,传递给 expression。
-
optionsLocatorEvaluateOptions?(optional)-
Timeout[float]? (optional)#等待定位器前评估的最长时间(以毫秒为单位)。请注意,在定位器解析之后,评估本身不受超时限制。默认值为
30000(30 秒)。传入0可禁用超时。
-
返回
- [object]#
详情
返回 expression 的返回值,该表达式以匹配的元素作为第一个参数,arg 作为第二个参数调用。
🌐 Returns the return value of expression, called with the matching element as a first argument, and arg as a second argument.
如果 expression 返回一个 Promise,此方法将等待该 Promise 解决并返回其值。
🌐 If expression returns a Promise, this method will wait for the promise to resolve and return its value.
如果 expression 抛出异常或被拒绝,则此方法会抛出异常。
🌐 If expression throws or rejects, this method throws.
EvaluateAllAsync
Added in: v1.14在页面中执行 JavaScript 代码,将所有匹配元素作为参数。
🌐 Execute JavaScript code in the page, taking all matching elements as an argument.
用法
var locator = page.Locator("div");
var moreThanTen = await locator.EvaluateAllAsync<bool>("(divs, min) => divs.length > min", 10);
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument? (optional)#可选参数,传递给 expression。
返回
- [object]#
详情
返回 expression 的返回值,该表达式以所有匹配元素组成的数组作为第一个参数,arg 作为第二个参数调用。
🌐 Returns the return value of expression, called with an array of all matching elements as a first argument, and arg as a second argument.
如果 expression 返回一个 Promise,此方法将等待该 Promise 解决并返回其值。
🌐 If expression returns a Promise, this method will wait for the promise to resolve and return its value.
如果 expression 抛出异常或拒绝,该方法会抛出异常。
🌐 If expression throws or rejects, this method throws.
EvaluateHandleAsync
Added in: v1.14在页面中执行 JavaScript 代码,将匹配的元素作为参数,并返回包含结果的 JSHandle。
🌐 Execute JavaScript code in the page, taking the matching element as an argument, and return a JSHandle with the result.
用法
await Locator.EvaluateHandleAsync(expression, arg, options);
参数
-
将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。
-
argEvaluationArgument? (optional)#可选参数,传递给 expression。
-
optionsLocatorEvaluateHandleOptions?(optional)-
Timeout[float]? (optional)#等待定位器前评估的最长时间(以毫秒为单位)。请注意,在定位器解析之后,评估本身不受超时限制。默认值为
30000(30 秒)。传入0可禁用超时。
-
返回
详情
返回 expression 的返回值作为 JSHandle,调用时将匹配的元素作为第一个参数,arg 作为第二个参数。
🌐 Returns the return value of expression as aJSHandle, called with the matching element as a first argument, and arg as a second argument.
Locator.EvaluateAsync() 和 Locator.EvaluateHandleAsync() 之间的唯一区别是 Locator.EvaluateHandleAsync() 返回 JSHandle。
🌐 The only difference between Locator.EvaluateAsync() and Locator.EvaluateHandleAsync() is that Locator.EvaluateHandleAsync() returns JSHandle.
如果 expression 返回一个 Promise,此方法将等待该 Promise 解决并返回其值。
🌐 If expression returns a Promise, this method will wait for the promise to resolve and return its value.
如果 expression 抛出异常或被拒绝,则此方法会抛出异常。
🌐 If expression throws or rejects, this method throws.
有关更多详情,请参阅 Page.EvaluateHandleAsync()。
🌐 See Page.EvaluateHandleAsync() for more details.
FillAsync
Added in: v1.14为输入字段设置一个值。
🌐 Set a value to the input field.
用法
await page.GetByRole(AriaRole.Textbox).FillAsync("example value");
参数
-
要为
<input>、<textarea>或[contenteditable]元素设置的值。 -
optionsLocatorFillOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
此方法等待 actionability 检查,聚焦元素,填写内容,并在填写后触发 input 事件。请注意,你可以传入空字符串以清空输入字段。
🌐 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.
如果目标元素不是 <input>、<textarea> 或 [contenteditable] 元素,该方法会抛出错误。不过,如果该元素位于具有关联 控件 的 <label> 元素内,则会填充控件。
🌐 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.
要发送精细的键盘事件,请使用 Locator.PressSequentiallyAsync()。
🌐 To send fine-grained keyboard events, use Locator.PressSequentiallyAsync().
Filter
Added in: v1.22此方法根据选项缩小现有定位器的范围,例如按文本过滤。它可以链式调用以多次过滤。
🌐 This method narrows existing locator according to the options, for example filters by text. It can be chained to filter multiple times.
用法
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();
参数
optionsLocatorFilterOptions?(optional)-
将方法的结果缩小到包含与此相对定位器匹配的元素的那些。例如,
article拥有text=Playwright匹配<article><div>Playwright</div></article>。内部定位器必须相对于外部定位器,并且查询从外部定位器匹配开始,而不是从文档根开始。例如,你可以找到包含
div的content,位于<article><content><div>Playwright</div></content></article>中。然而,查找包含article div的content会失败,因为内部定位器必须是相对的,不应使用content之外的任何元素。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
HasNotLocator? (optional) Added in: v1.33#匹配不包含与内层定位器匹配的元素的元素。内层定位器是在外层定位器范围内查询的。例如,不包含
div的article会匹配<article><span>Playwright</span></article>。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
HasNotText|HasNotTextRegexstring? | Regex? (optional) Added in: v1.33#匹配其内部(可能在子元素或后代元素中)不包含指定文本的元素。传入string时,匹配不区分大小写,并搜索子字符串。
-
HasText|HasTextRegexstring? | Regex? (optional)#匹配包含指定文本的元素,该文本可能位于子元素或后代元素中。如果传入一个[字符串],匹配不区分大小写,并搜索子字符串。例如,
"Playwright"可以匹配<article><div>Playwright</div></article>。 -
Visiblebool? (optional) Added in: v1.51#仅匹配可见或不可见元素。
-
返回
First
Added in: v1.14返回第一个匹配元素的定位器。
🌐 Returns locator to the first matching element.
用法
Locator.First
返回
FocusAsync
Added in: v1.14在匹配的元素上调用 focus。
🌐 Calls focus on the matching element.
用法
await Locator.FocusAsync(options);
参数
optionsLocatorFocusOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
FrameLocator
Added in: v1.17使用 iframe 时,你可以创建一个框架定位器,该定位器将进入 iframe 并允许定位该 iframe 中的元素:
🌐 When working with iframes, you can create a frame locator that will enter the iframe and allow locating elements in that iframe:
用法
var locator = page.FrameLocator("iframe").GetByText("Submit");
await locator.ClickAsync();
参数
返回
GetAttributeAsync
Added in: v1.14返回匹配元素的属性值。
🌐 Returns the matching element's attribute value.
如果你需要断言元素的属性,建议使用 Expect(Locator).ToHaveAttributeAsync() 来避免测试不稳定。更多详情请参见 断言指南。
🌐 If you need to assert an element's attribute, prefer Expect(Locator).ToHaveAttributeAsync() to avoid flakiness. See assertions guide for more details. :::
用法
await Locator.GetAttributeAsync(name, options);
参数
-
要获取其值的属性名称。
-
optionsLocatorGetAttributeOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
GetByAltText
Added in: v1.27允许通过替代文本定位元素。
🌐 Allows locating elements by their alt text.
用法
例如,此方法将通过替代文本“Playwright logo”来查找图片:
🌐 For example, this method will find the image by alt text "Playwright logo":
<img alt='Playwright logo'>
await page.GetByAltText("Playwright logo").ClickAsync();
参数
-
用于定位元素的文本。
-
optionsLocatorGetByAltTextOptions?(optional)
返回
GetByLabel
Added in: v1.27允许通过关联的 <label> 或 aria-labelledby 元素的文本,或通过 aria-label 属性来定位输入元素。
🌐 Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.
用法
例如,这种方法将在以下 DOM 中根据标签“用户名”和“密码”查找输入项:
🌐 For example, this method will find inputs by label "Username" and "Password" in the following DOM:
<input aria-label="Username">
<label for="password-input">Password:</label>
<input id="password-input">
await page.GetByLabel("Username").FillAsync("john");
await page.GetByLabel("Password").FillAsync("secret");
参数
-
用于定位元素的文本。
-
optionsLocatorGetByLabelOptions?(optional)
返回
GetByPlaceholder
Added in: v1.27允许通过占位符文本定位输入元素。
🌐 Allows locating input elements by the placeholder text.
用法
例如,考虑以下 DOM 结构。
🌐 For example, consider the following DOM structure.
<input type="email" placeholder="name@example.com" />
你可以在通过占位符文本找到输入后填充输入:
🌐 You can fill the input after locating it by the placeholder text:
await page
.GetByPlaceholder("name@example.com")
.FillAsync("playwright@microsoft.com");
参数
-
用于定位元素的文本。
-
optionsLocatorGetByPlaceholderOptions?(optional)
返回
GetByRole
Added in: v1.27允许通过元素的ARIA 角色、ARIA 属性和可访问名称来定位元素。
🌐 Allows locating elements by their ARIA role, ARIA attributes and accessible name.
用法
考虑以下 DOM 结构。
🌐 Consider the following DOM structure.
<h3>Sign up</h3>
<label>
<input type="checkbox" /> Subscribe
</label>
<br/>
<button>Submit</button>
你可以通过每个元素的隐式角色来定位它:
🌐 You can locate each element by it's implicit role:
await Expect(Page
.GetByRole(AriaRole.Heading, new() { Name = "Sign up" }))
.ToBeVisibleAsync();
await page
.GetByRole(AriaRole.Checkbox, new() { Name = "Subscribe" })
.CheckAsync();
await page
.GetByRole(AriaRole.Button, new() {
NameRegex = new Regex("submit", RegexOptions.IgnoreCase)
})
.ClickAsync();
参数
-
roleenum AriaRole { Alert, Alertdialog, Application, Article, Banner, Blockquote, Button, Caption, Cell, Checkbox, Code, Columnheader, Combobox, Complementary, Contentinfo, Definition, Deletion, Dialog, Directory, Document, Emphasis, Feed, Figure, Form, Generic, Grid, Gridcell, Group, Heading, Img, Insertion, Link, List, Listbox, Listitem, Log, Main, Marquee, Math, Meter, Menu, Menubar, Menuitem, Menuitemcheckbox, Menuitemradio, Navigation, None, Note, Option, Paragraph, Presentation, Progressbar, Radio, Radiogroup, Region, Row, Rowgroup, Rowheader, Scrollbar, Search, Searchbox, Separator, Slider, Spinbutton, Status, Strong, Subscript, Superscript, Switch, Tab, Table, Tablist, Tabpanel, Term, Textbox, Time, Timer, Toolbar, Tooltip, Tree, Treegrid, Treeitem }#所需的咏叹调角色。
-
optionsLocatorGetByRoleOptions?(optional)-
通常由
aria-checked或原生<input type=checkbox>控件设置的属性。了解更多关于
aria-checked的信息。 -
通常由
aria-disabled或disabled设置的属性。note与大多数其他属性不同,
disabled是通过 DOM 层级继承的。了解更多关于aria-disabled的信息。 -
Exactbool? (optional) Added in: v1.28#是否与 Name|NameRegex 完全匹配:区分大小写且匹配整个字符串。默认为 false。当 Name|NameRegex 是正则表达式时会被忽略。注意,完全匹配仍会去除空白字符。
-
通常由
aria-expanded设置的属性。了解更多关于
aria-expanded的信息。 -
IncludeHiddenbool? (optional)#控制是否匹配隐藏元素的选项。默认情况下,角色选择器仅匹配非隐藏元素,由 ARIA 定义。
了解更多关于
aria-hidden的信息。 -
一个通常存在于角色
heading、listitem、row、treeitem的数字属性,对<h1>-<h6>元素有默认值。了解更多关于
aria-level的信息。 -
Name|NameRegexstring? | Regex? (optional)#选项用于匹配可访问名称。默认情况下,匹配不区分大小写并搜索子字符串,使用精确可控制此行为。
了解有关可访问名称的更多信息。
-
通常由
aria-pressed设置的属性。了解更多关于
aria-pressed的信息。 -
通常由
aria-selected设置的属性。了解更多关于
aria-selected的信息。
-
返回
详情
角色选择器不能替代无障碍审查和符合性测试,而是提供关于ARIA指南的早期反馈。
🌐 Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
许多HTML元素都隐含着[定义角色](https://w3c.github.io/html-aam/#html-element-role-mappings),角色选择器会识别该角色。你可以在这里找到所有[支持的角色](https://www.w3.org/TR/wai-aria-1.2/#role_definitions)。ARIA 指南不建议通过将“role”和/或“aria-*”属性设置为默认值来重复隐式角色和属性。
🌐 Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines do not recommend duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.
GetByTestId
Added in: v1.27通过测试 ID 定位元素。
🌐 Locate element by the test id.
用法
考虑以下 DOM 结构。
🌐 Consider the following DOM structure.
<button data-testid="directions">Itinéraire</button>
你可以通过元素的测试 ID 来定位该元素:
🌐 You can locate the element by it's test id:
await page.GetByTestId("directions").ClickAsync();
参数
返回
详情
默认情况下,data-testid 属性用作测试 ID。如果有必要,可以使用 Selectors.SetTestIdAttribute() 来配置不同的测试 ID 属性。
🌐 By default, the data-testid attribute is used as a test id. Use Selectors.SetTestIdAttribute() to configure a different test id attribute if necessary.
GetByText
Added in: v1.27允许定位包含给定文本的元素。
🌐 Allows locating elements that contain given text.
另请参阅 Locator.Filter(),它允许按其他条件匹配,例如可访问角色,然后按文本内容进行筛选。
🌐 See also Locator.Filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.
用法
考虑以下 DOM 结构:
🌐 Consider the following DOM structure:
<div>Hello <span>world</span></div>
<div>Hello</div>
你可以通过文本子字符串、精确字符串或正则表达式进行定位:
🌐 You can locate by text substring, exact string, or a regular expression:
// Matches <span>
page.GetByText("world");
// Matches first <div>
page.GetByText("Hello world");
// Matches second <div>
page.GetByText("Hello", new() { Exact = true });
// Matches both <div>s
page.GetByText(new Regex("Hello"));
// Matches second <div>
page.GetByText(new Regex("^hello$", RegexOptions.IgnoreCase));
参数
-
用于定位元素的文本。
-
optionsLocatorGetByTextOptions?(optional)
返回
详情
文本匹配总是会规范化空白字符,即使是完全匹配。例如,它会将多个空格变为一个,将换行符变为空格,并忽略开头和结尾的空白。
🌐 Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
类型为 button 和 submit 的输入元素是通过它们的 value 而不是文本内容来匹配的。例如,通过文本 "Log in" 定位会匹配 <input type=button value="Log in">。
🌐 Input elements of the type button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.
GetByTitle
Added in: v1.27允许通过标题属性定位元素。
🌐 Allows locating elements by their title attribute.
用法
考虑以下 DOM 结构。
🌐 Consider the following DOM structure.
<span title='问题数量'>25 issues</span>
你可以通过标题文本找到问题后查看问题数:
🌐 You can check the issues count after locating it by the title text:
await Expect(Page.GetByTitle("Issues count")).toHaveText("25 issues");
参数
-
用于定位元素的文本。
-
optionsLocatorGetByTitleOptions?(optional)
返回
HighlightAsync
Added in: v1.20在屏幕上高亮相应的元素。对调试很有用,不要提交使用 Locator.HighlightAsync() 的代码。
🌐 Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses Locator.HighlightAsync().
用法
await Locator.HighlightAsync();
返回
HoverAsync
Added in: v1.14将鼠标悬停在匹配的元素上。
🌐 Hover over the matching element.
用法
await page.GetByRole(AriaRole.Link).HoverAsync();
参数
optionsLocatorHoverOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
ModifiersIEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
NoWaitAfterbool? (optional) Added in: v1.28#:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
PositionPosition? (optional)#-
X[float] -
Y[float]
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
-
返回
详情
此方法通过执行以下步骤将鼠标悬停在元素上:
🌐 This method hovers over the element by performing the following steps:
- 等待对该元素的可操作性检查,除非设置了强制选项。
- 如果需要,将元素滚动到视图中。
- 使用 Page.Mouse 将鼠标悬停在元素的中心,或指定的 Position 位置。
如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。
🌐 If the element is detached from the DOM at any moment during the action, this method throws.
当所有步骤在指定的 Timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
InnerHTMLAsync
Added in: v1.14🌐 Returns the element.innerHTML.
用法
await Locator.InnerHTMLAsync(options);
参数
optionsLocatorInnerHTMLOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
InnerTextAsync
Added in: v1.14🌐 Returns the element.innerText.
如果你需要断言页面上的文本,建议使用 Expect(Locator).ToHaveTextAsync() 并选择 UseInnerText 选项,以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert text on the page, prefer Expect(Locator).ToHaveTextAsync() with UseInnerText option to avoid flakiness. See assertions guide for more details. :::
用法
await Locator.InnerTextAsync(options);
参数
optionsLocatorInnerTextOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
InputValueAsync
Added in: v1.14返回匹配的 <input>、<textarea> 或 <select> 元素的值。
🌐 Returns the value for the matching <input> or <textarea> or <select> element.
如果你需要断言输入值,建议使用 Expect(Locator).ToHaveValueAsync() 以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert input value, prefer Expect(Locator).ToHaveValueAsync() to avoid flakiness. See assertions guide for more details.
用法
String value = await page.GetByRole(AriaRole.Textbox).InputValueAsync();
参数
optionsLocatorInputValueOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
抛出不是输入框、文本区域或选择框的元素。但是,如果元素位于具有关联控件的 <label> 元素内部,则返回该控件的值。
🌐 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.
IsCheckedAsync
Added in: v1.14返回元素是否被选中。如果元素不是复选框或单选按钮,将抛出异常。
🌐 Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
如果你需要断言复选框已被选中,建议使用 Expect(Locator).ToBeCheckedAsync() 以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert that checkbox is checked, prefer Expect(Locator).ToBeCheckedAsync() to avoid flakiness. See assertions guide for more details. :::
用法
var isChecked = await page.GetByRole(AriaRole.Checkbox).IsCheckedAsync();
参数
optionsLocatorIsCheckedOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
IsDisabledAsync
Added in: v1.14返回该元素是否被禁用,与enabled相反。
🌐 Returns whether the element is disabled, the opposite of enabled.
如果你需要断言一个元素是禁用的,建议使用 Expect(Locator).ToBeDisabledAsync() 以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert that an element is disabled, prefer Expect(Locator).ToBeDisabledAsync() to avoid flakiness. See assertions guide for more details.
用法
Boolean disabled = await page.GetByRole(AriaRole.Button).IsDisabledAsync();
参数
optionsLocatorIsDisabledOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
IsEditableAsync
Added in: v1.14返回元素是否为可编辑。如果目标元素不是 <input>、<textarea>、<select>、[contenteditable],且没有允许 [aria-readonly] 的角色,则此方法会抛出错误。
🌐 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.
如果你需要断言一个元素是可编辑的,建议使用 Expect(Locator).ToBeEditableAsync() 以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert that an element is editable, prefer Expect(Locator).ToBeEditableAsync() to avoid flakiness. See assertions guide for more details. :::
用法
Boolean editable = await page.GetByRole(AriaRole.Textbox).IsEditableAsync();
参数
optionsLocatorIsEditableOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
IsEnabledAsync
Added in: v1.14返回元素是否已启用。
🌐 Returns whether the element is enabled.
如果你需要断言一个元素是可用的,建议使用 Expect(Locator).ToBeEnabledAsync() 以避免不稳定。更多详情请参见 断言指南。
🌐 If you need to assert that an element is enabled, prefer Expect(Locator).ToBeEnabledAsync() to avoid flakiness. See assertions guide for more details. :::
用法
Boolean enabled = await page.GetByRole(AriaRole.Button).IsEnabledAsync();
参数
optionsLocatorIsEnabledOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
IsHiddenAsync
Added in: v1.14返回元素是否被隐藏,与 visible 相反。
🌐 Returns whether the element is hidden, the opposite of visible.
如果你需要断言某个元素是隐藏的,建议使用 Expect(Locator).ToBeHiddenAsync() 来避免不稳定性。更多详情请参考 断言指南。
🌐 If you need to assert that element is hidden, prefer Expect(Locator).ToBeHiddenAsync() to avoid flakiness. See assertions guide for more details.
用法
Boolean hidden = await page.GetByRole(AriaRole.Button).IsHiddenAsync();
参数
optionsLocatorIsHiddenOptions?(optional)-
Timeout[float]? (optional)#:::警告[已弃用] 这个选项被忽略了。[定位器。隐藏异步()](/api/class-locator.mdx#locator-is-hidden)不会等元素隐藏,立即返回。 :::
-
返回
IsVisibleAsync
Added in: v1.14返回元素是否可见。
🌐 Returns whether the element is visible.
如果你需要断言元素可见,建议使用 Expect(Locator).ToBeVisibleAsync() 来避免测试不稳定。更多详情请参见 断言指南。
🌐 If you need to assert that element is visible, prefer Expect(Locator).ToBeVisibleAsync() to avoid flakiness. See assertions guide for more details. :::
用法
Boolean visible = await page.GetByRole(AriaRole.Button).IsVisibleAsync();
参数
optionsLocatorIsVisibleOptions?(optional)-
Timeout[float]? (optional)#已弃用此选项会被忽略。Locator.IsVisibleAsync() 不会等待元素可见,而是会立即返回。
-
返回
Last
Added in: v1.14返回最后一个匹配元素的定位器。
🌐 Returns locator to the last matching element.
用法
var banana = await page.GetByRole(AriaRole.Listitem).Last(1);
返回
Locator
Added in: v1.14该方法在定位器的子树中查找与指定选择器匹配的元素。它还接受过滤选项,类似于 Locator.Filter() 方法。
🌐 The method finds an element matching the specified selector in the locator's subtree. It also accepts filter options, similar to Locator.Filter() method.
用法
Locator.Locator(selectorOrLocator, options);
参数
-
selectorOrLocatorstring | Locator#解析 DOM 元素时使用的选择器或定位器。
-
optionsLocatorLocatorOptions?(optional)-
将方法的结果缩小到包含与此相对定位器匹配的元素的那些。例如,
article拥有text=Playwright匹配<article><div>Playwright</div></article>。内部定位器必须相对于外部定位器,并且查询从外部定位器匹配开始,而不是从文档根开始。例如,你可以找到包含
div的content,位于<article><content><div>Playwright</div></content></article>中。然而,查找包含article div的content会失败,因为内部定位器必须是相对的,不应使用content之外的任何元素。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
HasNotLocator? (optional) Added in: v1.33#匹配不包含与内层定位器匹配的元素的元素。内层定位器是在外层定位器范围内查询的。例如,不包含
div的article会匹配<article><span>Playwright</span></article>。请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator。
-
HasNotText|HasNotTextRegexstring? | Regex? (optional) Added in: v1.33#匹配其内部(可能在子元素或后代元素中)不包含指定文本的元素。传入string时,匹配不区分大小写,并搜索子字符串。
-
HasText|HasTextRegexstring? | Regex? (optional)#匹配包含指定文本的元素,该文本可能位于子元素或后代元素中。如果传入一个[字符串],匹配不区分大小写,并搜索子字符串。例如,
"Playwright"可以匹配<article><div>Playwright</div></article>。
-
返回
Nth
Added in: v1.14返回第 n 个匹配元素的定位器。它是从零开始的,nth(0) 选择第一个元素。
🌐 Returns locator to the n-th matching element. It's zero based, nth(0) selects the first element.
用法
var banana = await page.GetByRole(AriaRole.Listitem).Nth(2);
参数
返回
Or
Added in: v1.33创建一个与匹配两个定位器中的一个或两个的所有元素匹配的定位器。
🌐 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.
用法
考虑这样一种情况:你想点击“新建邮件”按钮,但有时会出现安全设置对话框。在这种情况下,你可以等待“新建邮件”按钮或对话框的出现,并根据情况采取相应的操作。
🌐 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.
如果屏幕上同时出现“新建邮件”按钮和安全对话框,“或”定位器将匹配它们两者,可能会抛出“严格模式违规”错误。在这种情况下,你可以使用Locator.First只匹配其中一个。
🌐 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.
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();
参数
返回
Page
Added in: v1.19该定位器所属的页面。
🌐 A page this locator belongs to.
用法
Locator.Page
返回
PressAsync
Added in: v1.14聚焦匹配元素并按下组合键。
🌐 Focuses the matching element and presses a combination of the keys.
用法
await page.GetByRole(AriaRole.Textbox).PressAsync("Backspace");
参数
-
输入按键名称或生成字符名称,如“ArrowLeft”或“a”。
-
optionsLocatorPressOptions?(optional)-
Delay[float]? (optional)#keydown和keyup之间的等待时间,以毫秒为单位。默认值为 0。 -
已弃用
该选项将来默认值为
true。发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为
false。 -
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
聚焦该元素,然后使用 Keyboard.DownAsync() 和 Keyboard.UpAsync()。
🌐 Focuses the element, and then uses Keyboard.DownAsync() and Keyboard.UpAsync().
key 可以指定预期的 keyboardEvent.key 值或用于生成文本的单个字符。key 值的超集可以在 这里 找到。键的示例有:
F1 - F12、Digit0- Digit9、KeyA- KeyZ、Backquote、Minus、Equal、Backslash、Backspace、Tab、Delete、Escape、ArrowDown、End、Enter、Home、Insert、PageDown、PageUp、ArrowRight、ArrowUp,等等。
以下修改快捷键也受支持:Shift、Control、Alt、Meta、ShiftLeft、ControlOrMeta。ControlOrMeta 在 Windows 和 Linux 上解析为 Control,在 macOS 上解析为 Meta。
🌐 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.
按住 Shift 将会输入与大写形式的 key 对应的文本。
🌐 Holding down Shift will type the text that corresponds to the key in the upper case.
如果 key 是单个字符,则区分大小写,因此值 a 和 A 会生成不同的文本。
🌐 If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.
也支持诸如 key: "Control+o"、key: "Control++ 或 key: "Control+Shift+T" 之类的快捷键。当与修饰键一起指定时,在按下后续按键的同时按住修饰键。
🌐 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.
PressSequentiallyAsync
Added in: v1.38在大多数情况下,你应该使用 Locator.FillAsync()。只有在页面上有特殊的键盘处理时,你才需要逐个按键输入。
🌐 In most cases, you should use Locator.FillAsync() instead. You only need to press keys one by one if there is special keyboard handling on the page.
聚焦该元素,然后对文本中的每个字符发送 keydown、keypress/input 和 keyup 事件。
🌐 Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.
要按下特殊键,例如 Control 或 ArrowDown,请使用 Locator.PressAsync()。
🌐 To press a special key, like Control or ArrowDown, use Locator.PressAsync().
用法
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:
var locator = page.GetByLabel("Password");
await locator.PressSequentiallyAsync("my password");
await locator.PressAsync("Enter");
参数
-
要按顺序压入焦点元素的字符串。
-
optionsLocatorPressSequentiallyOptions?(optional)-
Delay[float]? (optional)#按键之间的等待时间,以毫秒为单位。默认为 0。
-
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
ScreenshotAsync
Added in: v1.14截取与定位器匹配的元素的屏幕截图。
🌐 Take a screenshot of the element matching the locator.
用法
await page.GetByRole(AriaRole.Link).ScreenshotAsync();
禁用动画并将屏幕截图保存到文件中:
🌐 Disable animations and save screenshot to a file:
await page.GetByRole(AriaRole.Link).ScreenshotAsync(new() {
Animations = ScreenshotAnimations.Disabled,
Path = "link.png"
});
参数
optionsLocatorScreenshotOptions?(optional)-
Animationsenum ScreenshotAnimations { Disabled, Allow }?(optional)#当设置为
"disabled"时,会停止 CSS 动画、CSS 过渡和 Web 动画。动画会根据其持续时间得到不同的处理:- 有限动画会被快进至完成,因此它们会触发
transitionend事件。 - 无限动画被取消到初始状态,然后在屏幕截图后播放。
默认值为
"allow",不会改变动画。 - 有限动画会被快进至完成,因此它们会触发
-
Caretenum ScreenshotCaret { Hide, Initial }?(optional)#当设置为
"hide"时,截图将隐藏文本光标。当设置为"initial"时,文本光标的行为不会改变。默认值为"hide"。 -
MaskIEnumerable?<Locator> (optional)#指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉红色的框
#FF00FF覆盖(可通过 MaskColor 自定义),完全覆盖其边界框。遮罩也会应用于不可见元素,参见 仅匹配可见元素 来禁用该功能。 -
MaskColorstring? (optional) Added in: v1.35#指定被遮罩元素的覆盖框颜色,使用 CSS 颜色格式。默认颜色是粉色
#FF00FF。 -
OmitBackgroundbool? (optional)#隐藏默认的白色背景,并允许捕获带透明度的截屏。不适用于
jpeg图片。默认值为false。 -
保存图片的文件路径。截图类型将根据文件扩展名来推断。如果 Path 是相对路径,则相对于当前工作目录解析。如果未提供路径,图片将不会保存到磁盘上。
-
图片质量,范围为0-100。不适用于
png图片。 -
Scaleenum ScreenshotScale { Css, Device }?(optional)#当设置为
"css"时,截图将每个页面的 CSS 像素对应一个像素。对于高分辨率设备,这将保持截图文件较小。使用"device"选项将每个设备像素对应一个像素,因此高分辨率设备的截图将会大两倍甚至更多。默认为
"device"。 -
Stylestring? (optional) Added in: v1.41#在截图时要应用的样式表文本。在这里,你可以隐藏动态元素,使元素不可见或更改它们的属性,以帮助你创建可重复的截图。此样式表可以穿透 Shadow DOM 并应用于内部框架。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
Typeenum ScreenshotType { Png, Jpeg }?(optional)#指定截图类型,默认为
png。
-
返回
详情
此方法会截取页面的屏幕截图,并裁剪到与匹配定位器的特定元素的大小和位置相符。如果该元素被其他元素覆盖,它在截图中实际上将不可见。如果该元素是可滚动的容器,则截图中只会显示当前滚动的内容。
🌐 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.
此方法会等待可操作性检查,然后将元素滚动到可视区域后再截图。如果元素已从 DOM 中分离,该方法会抛出错误。
🌐 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.
ScrollIntoViewIfNeededAsync
Added in: v1.14此方法会等待 actionability 检查,然后尝试将元素滚动到可见区域,除非它已经完全可见,如 IntersectionObserver 的 ratio 所定义。
🌐 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.
用法
await Locator.ScrollIntoViewIfNeededAsync(options);
参数
optionsLocatorScrollIntoViewIfNeededOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
SelectOptionAsync
Added in: v1.14在 <select> 中选择一个或多个选项。
🌐 Selects option or options in <select>.
用法
<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
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" });
参数
-
valuesstring | ElementHandle | IEnumerable |SelectOption| IEnumerable | IEnumerable?#-
Valuestring? (optional)比赛由“option.value”统计。可选。
-
Labelstring? (optional)由
option.label匹配。可选。 -
Indexint? (optional)按索引匹配。可选。
可选择的选项。如果
<select>拥有multiple属性,则所有匹配的选项都会被选中,否则只会选择与传入选项之一匹配的第一个选项。字符串值会同时匹配值和标签。如果所有指定的属性都匹配,则该选项被视为匹配。 -
-
optionsLocatorSelectOptionOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
此方法会等待 actionability 检查,等待直到 <select> 元素中出现所有指定选项,然后选择这些选项。
🌐 This method waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.
如果目标元素不是 <select> 元素,此方法将抛出错误。然而,如果该元素位于具有关联 控件 的 <label> 元素内,则会使用该控件。
🌐 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.
在所有提供的选项都被选择后,触发 change 和 input 事件。
🌐 Triggers a change and input event once all the provided options have been selected.
SelectTextAsync
Added in: v1.14该方法会等待可操作性检查,然后聚焦元素并选择其所有文本内容。
🌐 This method waits for actionability checks, then focuses the element and selects all its text content.
如果该元素位于具有相关控件的 <label> 元素内,则应聚焦并选择控件中的文本。
🌐 If the element is inside the <label> element that has an associated control, focuses and selects text in the control instead.
用法
await Locator.SelectTextAsync(options);
参数
optionsLocatorSelectTextOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
SetCheckedAsync
Added in: v1.15设置复选框或单选元素的状态。
🌐 Set the state of a checkbox or a radio element.
用法
await page.GetByRole(AriaRole.Checkbox).SetCheckedAsync(true);
参数
-
是否选中或取消选中复选框。
-
optionsLocatorSetCheckedOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
PositionPosition? (optional)#-
X[float] -
Y[float]
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
-
返回
详情
此方法通过执行以下步骤来检查或取消选中元素:
🌐 This method checks or unchecks an element by performing the following steps:
- 确保匹配的元素是复选框或单选按钮。如果不是,该方法将抛出异常。
- 如果元素已经具有正确的检查状态,则此方法立即返回。
- 等待匹配元素的可操作性检查,除非设置了强制选项。如果在检查期间元素被分离,整个操作将被重试。
- 如果需要,将元素滚动到视图中。
- 使用 Page.Mouse 点击元素的中心。
- 确保该元素现在已被选中或未被选中。如果没有,则此方法会抛出异常。
当所有步骤在指定的 Timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
SetInputFilesAsync
Added in: v1.14将文件或多个文件上传到 <input type=file>。对于具有 [webkitdirectory] 属性的输入,仅支持单个目录路径。
🌐 Upload file or multiple files into <input type=file>. For inputs with a [webkitdirectory] attribute, only a single directory path is supported.
用法
// 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"),
});
参数
-
filesstring | IEnumerable<string> |FilePayload| IEnumerable<FilePayload># -
optionsLocatorSetInputFilesOptions?(optional)-
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
详情
将文件输入的值设置为这些文件路径或文件。如果某些 filePaths 是相对路径,则会相对于当前工作目录进行解析。对于空数组,将清除已选的文件。
🌐 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.
此方法期望 Locator 指向一个 输入元素。但是,如果该元素位于具有关联 控件 的 <label> 元素内,则会定位到控件。
🌐 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.
TapAsync
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.
用法
await Locator.TapAsync(options);
参数
optionsLocatorTapOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
ModifiersIEnumerable?<enum KeyboardModifier { Alt, Control, ControlOrMeta, Meta, Shift }> (optional)#要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。
-
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
PositionPosition? (optional)#-
X[float] -
Y[float]
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论trial如何,键盘modifiers都会被按下,以便测试那些仅在按下这些键时才可见的元素。
-
返回
详情
此方法通过执行以下步骤来点击元素:
🌐 This method taps the element by performing the following steps:
- 等待对该元素的可操作性检查,除非设置了强制选项。
- 如果需要,将元素滚动到视图中。
- 使用 Page.Touchscreen 点击元素的中心,或指定的 Position。
如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。
🌐 If the element is detached from the DOM at any moment during the action, this method throws.
当所有步骤在指定的 Timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
element.tap() 要求将浏览器上下文的 hasTouch 选项设置为 true。
TextContentAsync
Added in: v1.14返回 node.textContent。
🌐 Returns the node.textContent.
如果你需要断言页面上的文本,建议使用 Expect(Locator).ToHaveTextAsync() 来避免测试不稳定。更多详情请参见 断言指南。
🌐 If you need to assert text on the page, prefer Expect(Locator).ToHaveTextAsync() to avoid flakiness. See assertions guide for more details. :::
用法
await Locator.TextContentAsync(options);
参数
optionsLocatorTextContentOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
UncheckAsync
Added in: v1.14确保复选框或单选元素未选中。
🌐 Ensure that checkbox or radio element is unchecked.
用法
await page.GetByRole(AriaRole.Checkbox).UncheckAsync();
参数
optionsLocatorUncheckOptions?(optional)-
是否绕过 可操作性 检查。默认值为
false。 -
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
PositionPosition? (optional)#-
X[float] -
Y[float]
相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。
-
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。 -
设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为
false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。
-
返回
详情
此方法通过执行以下步骤取消选中该元素:
🌐 This method unchecks the element by performing the following steps:
- 确保该元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经未选中,该方法会立即返回。
- 等待对该元素的可操作性检查,除非设置了强制选项。
- 如果需要,将元素滚动到视图中。
- 使用 Page.Mouse 点击元素的中心。
- 确保该元素现在未被选中。如果不是,这种方法会抛出异常。
如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。
🌐 If the element is detached from the DOM at any moment during the action, this method throws.
当所有步骤在指定的 Timeout 内未完成时,该方法会抛出 TimeoutError。传入零超时可禁用此功能。
🌐 When all steps combined have not finished during the specified Timeout, this method throws a TimeoutError. Passing zero timeout disables this.
WaitForAsync
Added in: v1.16当由定位器指定的元素满足 State 选项时返回。
🌐 Returns when element specified by locator satisfies the State option.
如果目标元素已经满足条件,该方法会立即返回。否则,将等待最多 Timeout 毫秒,直到条件满足。
🌐 If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to Timeout milliseconds until the condition is met.
用法
var orderSent = page.Locator("#order-sent");
orderSent.WaitForAsync();
参数
optionsLocatorWaitForOptions?(optional)-
Stateenum WaitForSelectorState { Attached, Detached, Visible, Hidden }?(optional)#默认值为
'visible'。可以是以下之一:'attached'- 等待元素出现在 DOM 中。'detached'- 等待元素不再出现在 DOM 中。'visible'- 等待元素有非空的边界框并且不含visibility:hidden。请注意,没有任何内容或含有display:none的元素会有空的边界框,并且不被认为是可见的。'hidden'- 等待元素被从 DOM 中移除,或其边界框为空,或为visibility:hidden。这与'visible'选项相反。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
已弃用
🌐 Deprecated
ElementHandleAsync
Added in: v1.14始终优先使用 Locator 和网页断言,而不是 ElementHandle,因为后者本质上容易出现竞争条件。
🌐 Always prefer using Locators and web assertions over ElementHandles because latter are inherently racy.
将给定的定位器解析为第一个匹配的 DOM 元素。如果没有匹配的元素,则等待出现。如果有多个元素匹配该定位器,则抛出异常。
🌐 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.
用法
await Locator.ElementHandleAsync(options);
参数
optionsLocatorElementHandleOptions?(optional)-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回
ElementHandlesAsync
Added in: v1.14始终优先使用 Locator 和网页断言,而不是 ElementHandle,因为后者本质上容易出现竞争条件。
🌐 Always prefer using Locators and web assertions over ElementHandles because latter are inherently racy.
将给定的定位器解析为所有匹配的 DOM 元素。如果没有匹配的元素,则返回空列表。
🌐 Resolves given locator to all matching DOM elements. If there are no matching elements, returns an empty list.
用法
await Locator.ElementHandlesAsync();
返回
TypeAsync
Added in: v1.14在大多数情况下,你应该使用 Locator.FillAsync()。只有在页面上需要特殊的键盘处理时,才需要逐个按键——在这种情况下使用 Locator.PressSequentiallyAsync()。
🌐 In most cases, you should use Locator.FillAsync() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use Locator.PressSequentiallyAsync().
聚焦该元素,然后对文本中的每个字符发送 keydown、keypress/input 和 keyup 事件。
🌐 Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.
要按下特殊键,例如 Control 或 ArrowDown,请使用 Locator.PressAsync()。
🌐 To press a special key, like Control or ArrowDown, use Locator.PressAsync().
用法
参数
-
要输入到焦点元素中的文本。
-
optionsLocatorTypeOptions?(optional)-
Delay[float]? (optional)#按键之间的等待时间,以毫秒为单位。默认为 0。
-
:::警告[已弃用] 这个选项没有效果。 :::
此选项无效。
-
Timeout[float]? (optional)#最长时间(以毫秒为单位)。默认值为
30000(30 秒)。传入0可禁用超时。默认值可以通过使用 BrowserContext.SetDefaultTimeout() 或 Page.SetDefaultTimeout() 方法进行更改。
-
返回