Skip to main content

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

all

Added in: v1.29 locator.all

当定位器指向元素列表时,这将返回一个定位器数组,指向它们各自的元素。

🌐 When the locator points to a list of elements, this returns an array of locators, pointing to their respective elements.

note

locator.all() 不会等待元素匹配定位器,而是会立即返回页面上当前存在的内容。

当元素列表动态变化时,locator.all() 会产生不可预测且不稳定的结果。

🌐 When the list of elements changes dynamically, locator.all() will produce unpredictable and flaky results.

当元素列表是稳定的,但动态加载时,在调用 locator.all() 之前,等待完整列表加载完成。

🌐 When the list of elements is stable, but loaded dynamically, wait for the full list to finish loading before calling locator.all().

用法

for li in page.get_by_role('listitem').all():
li.click();

返回


all_inner_texts

Added in: v1.14 locator.all_inner_texts

返回所有匹配节点的 node.innerText 值数组。

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

Asserting text

如果你需要断言页面上的文本,建议使用 expect(locator).to_have_text() 并配合 use_inner_text 选项以避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert text on the page, prefer expect(locator).to_have_text() with use_inner_text option to avoid flakiness. See assertions guide for more details. :::

用法

texts = page.get_by_role("link").all_inner_texts()

返回


all_text_contents

Added in: v1.14 locator.all_text_contents

返回所有匹配节点的 node.textContent 值数组。

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

Asserting text

如果你需要断言页面上的文本,建议使用 expect(locator).to_have_text() 以避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert text on the page, prefer expect(locator).to_have_text() to avoid flakiness. See assertions guide for more details.

用法

texts = page.get_by_role("link").all_text_contents()

返回


and_

Added in: v1.34 locator.and_

创建一个与此定位器和参数定位器相匹配的定位器。

🌐 Creates a locator that matches both this locator and the argument locator.

用法

以下示例查找具有特定标题的按钮。

🌐 The following example finds a button with a specific title.

button = page.get_by_role("button").and_(page.get_by_title("Subscribe"))

参数

  • locator Locator#

    要匹配的附加定位器。

返回


aria_snapshot

Added in: v1.49 locator.aria_snapshot

捕获给定元素的 aria 快照。阅读更多关于 aria 快照expect(locator).to_match_aria_snapshot() 的信息,以进行相应的断言。

🌐 Captures the aria snapshot of the given element. Read more about aria snapshots and expect(locator).to_match_aria_snapshot() for the corresponding assertion.

用法

page.get_by_role("link").aria_snapshot()

参数

返回

详情

此方法捕获给定元素的 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"

blur

Added in: v1.28 locator.blur

在该元素上调用 blur 方法。

🌐 Calls blur on the element.

用法

locator.blur()
locator.blur(**kwargs)

参数

返回


bounding_box

Added in: v1.14 locator.bounding_box

该方法返回与定位符匹配元素的边界框,若元素不可见则返回“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.

用法

box = page.get_by_role("button").bounding_box()
page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)

参数

返回

  • NoneType | Dict#
    • 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.


check

Added in: v1.14 locator.check

确保复选框或单选元素已选中。

🌐 Ensure that checkbox or radio element is checked.

用法

page.get_by_role("checkbox").check()

参数

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • position Dict (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回

详情

执行以下步骤:

🌐 Performs the following steps:

  1. 确保该元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经被选中,该方法会立即返回。
  2. 等待对该元素进行可操作性检查,除非设置了强制选项。
  3. 如果需要,将元素滚动到视图中。
  4. 使用 page.mouse 点击元素的中心。
  5. 确保该元素现在已被选中。如果没有,该方法会抛出异常。

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。

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


clear

Added in: v1.28 locator.clear

清除输入字段。

🌐 Clear the input field.

用法

page.get_by_role("textbox").clear()

参数

返回

详情

此方法会等待 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.


click

Added in: v1.14 locator.click

单击一个元素。

🌐 Click an element.

用法

单击一个按钮:

🌐 Click a button:

page.get_by_role("button").click()

按住 Shift 键并右键单击画布上的特定位置:

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

page.locator("canvas").click(
button="right", modifiers=["Shift"], position={"x": 23, "y": 32}
)

参数

  • button "left" | "right" | "middle" (optional)#

    默认为 left

  • click_count int (optional)#

    默认为 1。请参阅 UIEvent.detail

  • delay float (optional)#

    mousedownmouseup 之间的等待时间,以毫秒为单位。默认值为 0。

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • modifiers List["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#

    要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

  • no_wait_after bool (optional)#

    已弃用

    此选项将来默认值为 true

    发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为 false

  • position Dict (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • steps int (optional) Added in: v1.57#

    默认为1。发送 n 个插值的 mousemove 事件,以表示从 Playwright 当前光标位置到指定目的地的移动。当设置为1时,在目标位置只发出一个 mousemove 事件。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论 trial 如何,键盘 modifiers 都会被按下,以便测试那些仅在按下这些键时才可见的元素。

返回

详情

此方法通过执行以下步骤来单击元素:

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

  1. 等待对该元素进行可操作性检查,除非设置了强制选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 page.mouse 点击元素中心,或指定的 position 位置。
  4. 等待已启动的导航要么成功,要么失败,除非设置了 no_wait_after 选项。

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。

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


count

Added in: v1.14 locator.count

返回与定位器匹配的元素数。

🌐 Returns the number of elements matching the locator.

Asserting count

如果你需要断言页面上的元素数量,建议使用 expect(locator).to_have_count() 来避免测试不稳定。更多详情请参见 断言指南

🌐 If you need to assert the number of elements on the page, prefer expect(locator).to_have_count() to avoid flakiness. See assertions guide for more details. :::

用法

count = page.get_by_role("listitem").count()

返回


dblclick

Added in: v1.14 locator.dblclick

双击一个元素。

🌐 Double-click an element.

用法

locator.dblclick()
locator.dblclick(**kwargs)

参数

  • button "left" | "right" | "middle" (optional)#

    默认为 left

  • delay float (optional)#

    mousedownmouseup 之间的等待时间,以毫秒为单位。默认值为 0。

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • modifiers List["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#

    要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • position Dict (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • steps int (optional) Added in: v1.57#

    默认为1。发送 n 个插值的 mousemove 事件,以表示从 Playwright 当前光标位置到指定目的地的移动。当设置为1时,在目标位置只发出一个 mousemove 事件。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论 trial 如何,键盘 modifiers 都会被按下,以便测试那些仅在按下这些键时才可见的元素。

返回

详情

此方法通过执行以下步骤双击该元素:

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

  1. 等待对该元素的可操作性检查,除非设置了强制选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 page.mouse 在元素中心或指定的 position 双击。

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时将禁用此功能。

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

note

element.dblclick() 触发两个 click 事件和一个 dblclick 事件。


describe

Added in: v1.53locator.describe

描述定位器,描述用于跟踪查看器和报告中。返回指向同一元素的定位器。

🌐 Describes the locator, description is used in the trace viewer and reports. Returns the locator pointing to the same element.

用法

button = page.get_by_test_id("btn-sub").describe("Subscribe button")
button.click()

参数

  • description str#

    定位器描述。

返回


dispatch_event

Added in: v1.14locator.dispatch_event

以编程方式在匹配元素上调度事件。

🌐 Programmatically dispatch an event on the matching element.

用法

locator.dispatch_event("click")

参数

返回

详情

上面的代码片段会在该元素上触发 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 创建一个事件实例,使用 event_init 属性初始化它,并在元素上派发该事件。事件类型是 composedcancelable,默认情况下会冒泡。

🌐 Under the hood, it creates an instance of an event based on the given type, initializes it with event_init properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

由于 event_init 是特定于事件的,请查阅事件文档以获取初始属性列表:

🌐 Since event_init is event-specific, please refer to the events documentation for the lists of initial properties:

如果你希望将实时对象传递到事件中,你也可以将 JSHandle 指定为属性值:

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

data_transfer = page.evaluate_handle("new DataTransfer()")
locator.dispatch_event("#source", "dragstart", {"dataTransfer": data_transfer})

drag_to

Added in: v1.18locator.drag_to

将源元素拖向目标元素并将其放下。

🌐 Drag the source element towards the target element and drop it.

用法

source = page.locator("#source")
target = page.locator("#target")

source.drag_to(target)
# or specify exact positions relative to the top-left corners of the elements:
source.drag_to(
target,
source_position={"x": 34, "y": 7},
target_position={"x": 10, "y": 20}
)

参数

  • target Locator#

    要拖动到的元素的定位器。

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

此选项无效。

  • source_position Dict (optional)#

    在此位置点击源元素,相对于元素内边距框的左上角。如果未指定,则使用元素的某个可见点。

  • steps int (optional) Added in: v1.57#

    默认为 1。发送 n 个插值的 mousemove 事件以表示拖动的 mousedownmouseup 之间的移动。当设置为 1 时,在目标位置仅触发一个 mousemove 事件。

  • target_position Dict (optional)#

    在此点相对于元素填充框左上角投放目标元素。如果未指定,则使用元素的某个可见点。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 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.


evaluate

Added in: v1.14 locator.evaluate

在页面中执行 JavaScript 代码,将匹配元素作为参数。

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

用法

将参数传递给 expression

🌐 Passing argument to expression:

result = page.get_by_testid("myId").evaluate("(element, [x, y]) => element.textContent + ' ' + x * y", [7, 8])
print(result) # prints "myId text 56"

参数

  • expression str#

    将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。

  • arg EvaluationArgument (optional)#

    可选参数,传递给 expression

  • timeout float (optional)#

    等待定位器前评估的最长时间(以毫秒为单位)。请注意,在定位器解析之后,评估本身不受超时限制。默认值为 30000(30 秒)。传入 0 可禁用超时。

返回

详情

返回 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.


evaluate_all

Added in: v1.14 locator.evaluate_all

在页面中执行 JavaScript 代码,将所有匹配元素作为参数。

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

用法

locator = page.locator("div")
more_than_ten = locator.evaluate_all("(divs, min) => divs.length > min", 10)

参数

  • expression str#

    将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。

  • arg EvaluationArgument (optional)#

    可选参数,传递给 expression

返回

详情

返回 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.


evaluate_handle

Added in: v1.14 locator.evaluate_handle

在页面中执行 JavaScript 代码,将匹配的元素作为参数,并返回包含结果的 JSHandle

🌐 Execute JavaScript code in the page, taking the matching element as an argument, and return a JSHandle with the result.

用法

locator.evaluate_handle(expression)
locator.evaluate_handle(expression, **kwargs)

参数

  • expression str#

    将在浏览器上下文中求值的 JavaScript 表达式。如果表达式求值为一个函数,该函数将被自动调用。

  • arg EvaluationArgument (optional)#

    可选参数,传递给 expression

  • 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.evaluate()locator.evaluate_handle() 唯一的区别是 locator.evaluate_handle() 返回 JSHandle

🌐 The only difference between locator.evaluate() and locator.evaluate_handle() is that locator.evaluate_handle() 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.evaluate_handle()

🌐 See page.evaluate_handle() for more details.


fill

Added in: v1.14 locator.fill

为输入字段设置一个值。

🌐 Set a value to the input field.

用法

page.get_by_role("textbox").fill("example value")

参数

  • value str#

    要为 <input><textarea>[contenteditable] 元素设置的值。

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

返回

详情

此方法等待 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.press_sequentially()

🌐 To send fine-grained keyboard events, use locator.press_sequentially().


filter

Added in: v1.22 locator.filter

此方法根据选项缩小现有定位器的范围,例如按文本过滤。它可以链式调用以多次过滤。

🌐 This method narrows existing locator according to the options, for example filters by text. It can be chained to filter multiple times.

用法

row_locator = page.locator("tr")
# ...
row_locator.filter(has_text="text in column 1").filter(
has=page.get_by_role("button", name="column 2 button")
).screenshot()

参数

  • has Locator (optional)#

    将方法的结果缩小到包含与此相对定位器匹配的元素的那些。例如,article 拥有 text=Playwright 匹配 <article><div>Playwright</div></article>

    内部定位器必须相对于外部定位器,并且查询从外部定位器匹配开始,而不是从文档根开始。例如,你可以找到包含 divcontent,位于 <article><content><div>Playwright</div></content></article> 中。然而,查找包含 article divcontent 会失败,因为内部定位器必须是相对的,不应使用 content 之外的任何元素。

    请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator

  • has_not Locator (optional) Added in: v1.33#

    匹配不包含与内层定位器匹配的元素的元素。内层定位器是在外层定位器范围内查询的。例如,不包含 divarticle 会匹配 <article><span>Playwright</span></article>

    请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator

  • has_not_text str | Pattern (optional) Added in: v1.33#

    匹配其内部(可能在子元素或后代元素中)不包含指定文本的元素。传入[string]时,匹配不区分大小写,并搜索子字符串。

  • has_text str | Pattern (optional)#

    匹配包含指定文本的元素,该文本可能位于子元素或后代元素中。如果传入一个[字符串],匹配不区分大小写,并搜索子字符串。例如,"Playwright" 可以匹配 <article><div>Playwright</div></article>

  • visible bool (optional) Added in: v1.51#

    仅匹配可见或不可见元素。

返回


focus

Added in: v1.14 locator.focus

在匹配的元素上调用 focus

🌐 Calls focus on the matching element.

用法

locator.focus()
locator.focus(**kwargs)

参数

返回


frame_locator

Added in: v1.17 locator.frame_locator

使用 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:

用法

locator = page.frame_locator("iframe").get_by_text("Submit")
locator.click()

参数

  • selector str#

    解析 DOM 元素时使用的选择器。

返回


get_attribute

Added in: v1.14 locator.get_attribute

返回匹配元素的属性值。

🌐 Returns the matching element's attribute value.

Asserting attributes

如果你需要断言元素的属性,建议使用 expect(locator).to_have_attribute() 以避免不稳定性。更多详情请参见 断言指南

🌐 If you need to assert an element's attribute, prefer expect(locator).to_have_attribute() to avoid flakiness. See assertions guide for more details.

用法

locator.get_attribute(name)
locator.get_attribute(name, **kwargs)

参数

返回


get_by_alt_text

Added in: v1.27 locator.get_by_alt_text

允许通过替代文本定位元素。

🌐 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'>
page.get_by_alt_text("Playwright logo").click()

参数

  • text str | Pattern#

    用于定位元素的文本。

  • exact bool (optional)#

    是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。

返回


get_by_label

Added in: v1.27 locator.get_by_label

允许通过关联的 <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">
page.get_by_label("Username").fill("john")
page.get_by_label("Password").fill("secret")

参数

  • text str | Pattern#

    用于定位元素的文本。

  • exact bool (optional)#

    是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。

返回


get_by_placeholder

Added in: v1.27 locator.get_by_placeholder

允许通过占位符文本定位输入元素。

🌐 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:

page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")

参数

  • text str | Pattern#

    用于定位元素的文本。

  • exact bool (optional)#

    是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。

返回


get_by_role

Added in: v1.27 locator.get_by_role

允许通过元素的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:

expect(page.get_by_role("heading", name="Sign up")).to_be_visible()

page.get_by_role("checkbox", name="Subscribe").check()

page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()

参数

  • role "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"#

    所需的咏叹调角色。

  • checked bool (optional)#

    通常由 aria-checked 或原生 <input type=checkbox> 控件设置的属性。

    了解更多关于 aria-checked 的信息。

  • disabled bool (optional)#

    通常由 aria-disableddisabled 设置的属性。

    note

    与大多数其他属性不同,disabled 是通过 DOM 层级继承的。了解更多关于 aria-disabled 的信息。

  • exact bool (optional) Added in: v1.28#

    是否与name完全匹配:区分大小写且匹配整个字符串。默认为 false。当name是正则表达式时将被忽略。请注意,完全匹配仍会去除空格。

  • expanded bool (optional)#

    通常由 aria-expanded 设置的属性。

    了解更多关于 aria-expanded 的信息。

  • include_hidden bool (optional)#

    控制是否匹配隐藏元素的选项。默认情况下,角色选择器仅匹配非隐藏元素,由 ARIA 定义

    了解更多关于 aria-hidden 的信息。

  • level int (optional)#

    一个通常存在于角色 headinglistitemrowtreeitem 的数字属性,对 <h1>-<h6> 元素有默认值。

    了解更多关于 aria-level 的信息。

  • name str | Pattern (optional)#

    选项用于匹配可访问名称。默认情况下,匹配不区分大小写并搜索子字符串,使用精确可控制此行为。

    了解有关可访问名称的更多信息。

  • pressed bool (optional)#

    通常由 aria-pressed 设置的属性。

    了解更多关于 aria-pressed 的信息。

  • selected bool (optional)#

    通常由 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.


get_by_test_id

Added in: v1.27 locator.get_by_test_id

通过测试 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:

page.get_by_test_id("directions").click()

参数

返回

详情

默认情况下,'data-testid' 属性被用作测试 ID。如有需要,使用 [selectors.set_test_id_attribute()](/api/class-selectors.mdx#selectors-set-test-id-attribute) 配置不同的测试 ID 属性。

🌐 By default, the data-testid attribute is used as a test id. Use selectors.set_test_id_attribute() to configure a different test id attribute if necessary.


get_by_text

Added in: v1.27 locator.get_by_text

允许定位包含给定文本的元素。

🌐 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.get_by_text("world")

# Matches first <div>
page.get_by_text("Hello world")

# Matches second <div>
page.get_by_text("Hello", exact=True)

# Matches both <div>s
page.get_by_text(re.compile("Hello"))

# Matches second <div>
page.get_by_text(re.compile("^hello$", re.IGNORECASE))

参数

  • text str | Pattern#

    用于定位元素的文本。

  • exact bool (optional)#

    是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。

返回

详情

文本匹配总是会规范化空白字符,即使是完全匹配。例如,它会将多个空格变为一个,将换行符变为空格,并忽略开头和结尾的空白。

🌐 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.

类型为 buttonsubmit 的输入元素是通过它们的 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">.


get_by_title

Added in: v1.27 locator.get_by_title

允许通过标题属性定位元素。

🌐 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:

expect(page.get_by_title("Issues count")).to_have_text("25 issues")

参数

  • text str | Pattern#

    用于定位元素的文本。

  • exact bool (optional)#

    是否查找完全匹配:区分大小写并匹配整个字符串。默认为 false。在通过正则表达式定位时会被忽略。请注意,完全匹配仍会去除空白字符。

返回


highlight

Added in: v1.20 locator.highlight

在屏幕上高亮相应的元素。用于调试时很有用,不要提交使用 locator.highlight() 的代码。

🌐 Highlight the corresponding element(s) on the screen. Useful for debugging, don't commit the code that uses locator.highlight().

用法

locator.highlight()

返回


hover

Added in: v1.14 locator.hover

将鼠标悬停在匹配的元素上。

🌐 Hover over the matching element.

用法

page.get_by_role("link").hover()

参数

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • modifiers List["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#

    要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

  • no_wait_after bool (optional) Added in: v1.28#

    已弃用

    此选项无效。

    此选项无效。

  • position Dict (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论 trial 如何,键盘 modifiers 都会被按下,以便测试那些仅在按下这些键时才可见的元素。

返回

详情

此方法通过执行以下步骤将鼠标悬停在元素上:

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

  1. 等待元素的[作性](../actionability.mdx)检定,除非设置了[强制](/api/class-locator.mdx#locator-hover-option-force)选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 page.mouse 将鼠标悬停在元素的中心,或指定的 position 位置。

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。

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


inner_html

Added in: v1.14 locator.inner_html

返回 element.innerHTML

🌐 Returns the element.innerHTML.

用法

locator.inner_html()
locator.inner_html(**kwargs)

参数

返回


inner_text

Added in: v1.14 locator.inner_text

返回 element.innerText

🌐 Returns the element.innerText.

Asserting text

如果你需要断言页面上的文本,建议使用 expect(locator).to_have_text() 并配合 use_inner_text 选项以避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert text on the page, prefer expect(locator).to_have_text() with use_inner_text option to avoid flakiness. See assertions guide for more details. :::

用法

locator.inner_text()
locator.inner_text(**kwargs)

参数

返回


input_value

Added in: v1.14 locator.input_value

返回匹配的 <input><textarea><select> 元素的值。

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

Asserting value

如果你需要断言输入值,建议使用 expect(locator).to_have_value() 来避免不稳定。更多详细信息请参阅 断言指南

🌐 If you need to assert input value, prefer expect(locator).to_have_value() to avoid flakiness. See assertions guide for more details. :::

用法

value = page.get_by_role("textbox").input_value()

参数

返回

详情

抛出不是输入框、文本区域或选择框的元素。但是,如果元素位于具有关联控件<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.


is_checked

Added in: v1.14 locator.is_checked

返回元素是否被选中。如果元素不是复选框或单选按钮,将抛出异常。

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

Asserting checked state

如果你需要确认复选框已被选中,建议使用 expect(locator).to_be_checked() 来避免测试不稳定。更多详情请参阅 断言指南

🌐 If you need to assert that checkbox is checked, prefer expect(locator).to_be_checked() to avoid flakiness. See assertions guide for more details.

用法

checked = page.get_by_role("checkbox").is_checked()

参数

返回


is_disabled

Added in: v1.14 locator.is_disabled

返回该元素是否被禁用,与enabled相反。

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

Asserting disabled state

如果你需要断言某个元素是禁用的,建议使用 expect(locator).to_be_disabled() 来避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert that an element is disabled, prefer expect(locator).to_be_disabled() to avoid flakiness. See assertions guide for more details. :::

用法

disabled = page.get_by_role("button").is_disabled()

参数

返回


is_editable

Added in: v1.14 locator.is_editable

返回元素是否为可编辑。如果目标元素不是 <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.

Asserting editable state

如果你需要断言一个元素是可编辑的,优先使用 expect(locator).to_be_editable() 以避免不稳定性。更多详情请参见 断言指南

🌐 If you need to assert that an element is editable, prefer expect(locator).to_be_editable() to avoid flakiness. See assertions guide for more details.

用法

editable = page.get_by_role("textbox").is_editable()

参数

返回


is_enabled

Added in: v1.14 locator.is_enabled

返回元素是否已启用

🌐 Returns whether the element is enabled.

Asserting enabled state

如果你需要断言某个元素是可用的,建议使用 expect(locator).to_be_enabled() 来避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert that an element is enabled, prefer expect(locator).to_be_enabled() to avoid flakiness. See assertions guide for more details. :::

用法

enabled = page.get_by_role("button").is_enabled()

参数

返回


is_hidden

Added in: v1.14 locator.is_hidden

返回元素是否被隐藏,与 visible 相反。

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

Asserting visibility

如果你需要断言元素是隐藏的,建议使用 expect(locator).to_be_hidden() 以避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert that element is hidden, prefer expect(locator).to_be_hidden() to avoid flakiness. See assertions guide for more details.

用法

hidden = page.get_by_role("button").is_hidden()

参数

  • timeout float (optional)#

    已弃用

    该选项会被忽略。locator.is_hidden() 不会等待元素隐藏,会立即返回。

返回


is_visible

Added in: v1.14 locator.is_visible

返回元素是否可见

🌐 Returns whether the element is visible.

Asserting visibility

如果你需要断言元素是可见的,建议使用 expect(locator).to_be_visible() 来避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert that element is visible, prefer expect(locator).to_be_visible() to avoid flakiness. See assertions guide for more details.

用法

visible = page.get_by_role("button").is_visible()

参数

  • timeout float (optional)#

    已弃用

    该选项会被忽略。locator.is_visible() 不会等待元素变为可见,并会立即返回。

返回


locator

Added in: v1.14 locator.locator

该方法在定位子树中找到与指定选择符匹配的元素。它还接受过滤选项,类似于 [locator.filter()](/api/class-locator.mdx#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(selector_or_locator)
locator.locator(selector_or_locator, **kwargs)

参数

  • selector_or_locator str | Locator#

    解析 DOM 元素时使用的选择器或定位器。

  • has Locator (optional)#

    将方法的结果缩小到包含与此相对定位器匹配的元素的那些。例如,article 拥有 text=Playwright 匹配 <article><div>Playwright</div></article>

    内部定位器必须相对于外部定位器,并且查询从外部定位器匹配开始,而不是从文档根开始。例如,你可以找到包含 divcontent,位于 <article><content><div>Playwright</div></content></article> 中。然而,查找包含 article divcontent 会失败,因为内部定位器必须是相对的,不应使用 content 之外的任何元素。

    请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator

  • has_not Locator (optional) Added in: v1.33#

    匹配不包含与内层定位器匹配的元素的元素。内层定位器是在外层定位器范围内查询的。例如,不包含 divarticle 会匹配 <article><span>Playwright</span></article>

    请注意,外部定位器和内部定位器必须属于同一帧。内部定位器不能包含 FrameLocator

  • has_not_text str | Pattern (optional) Added in: v1.33#

    匹配其内部(可能在子元素或后代元素中)不包含指定文本的元素。传入[string]时,匹配不区分大小写,并搜索子字符串。

  • has_text str | Pattern (optional)#

    匹配包含指定文本的元素,该文本可能位于子元素或后代元素中。如果传入一个[字符串],匹配不区分大小写,并搜索子字符串。例如,"Playwright" 可以匹配 <article><div>Playwright</div></article>

返回


nth

Added in: v1.14 locator.nth

返回第 n 个匹配元素的定位器。它是从零开始的,nth(0) 选择第一个元素。

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

用法

banana = page.get_by_role("listitem").nth(2)

参数

返回


or_

Added in: v1.33 locator.or_

创建一个与匹配两个定位器中的一个或两个的所有元素匹配的定位器。

🌐 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.

note

如果屏幕上同时出现“新建邮件”按钮和安全对话框,“或”定位器将匹配它们两者,可能会抛出严格模式违规错误。在这种情况下,你可以使用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.

new_email = page.get_by_role("button", name="New")
dialog = page.get_by_text("Confirm security settings")
expect(new_email.or_(dialog).first).to_be_visible()
if (dialog.is_visible()):
page.get_by_role("button", name="Dismiss").click()
new_email.click()

参数

  • locator Locator#

    要匹配的替代定位器。

返回


press

Added in: v1.14 locator.press

聚焦匹配元素并按下组合键。

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

用法

page.get_by_role("textbox").press("Backspace")

参数

  • key str#

    输入按键名称或生成字符名称,如“ArrowLeft”或“a”。

  • delay float (optional)#

    keydownkeyup 之间的等待时间,以毫秒为单位。默认值为 0。

  • no_wait_after bool (optional)#

    已弃用

    此选项将来默认值为 true

    发起导航的操作会等待这些导航发生并且页面开始加载。你可以通过设置此标志选择不等待。你通常只有在特殊情况下(例如导航到无法访问的页面)才需要此选项。默认值为 false

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

返回

详情

聚焦元素,然后使用 keyboard.down()keyboard.up()

🌐 Focuses the element, and then uses keyboard.down() and keyboard.up().

key 可以指定预期的 keyboardEvent.key 值或用于生成文本的单个字符。key 值的超集可以在 这里 找到。键的示例有:

F1 - F12Digit0- Digit9KeyA- KeyZBackquoteMinusEqualBackslashBackspaceTabDeleteEscapeArrowDownEndEnterHomeInsertPageDownPageUpArrowRightArrowUp,等等。

以下修改快捷键也受支持:ShiftControlAltMetaShiftLeftControlOrMetaControlOrMeta 在 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 是单个字符,则区分大小写,因此值 aA 会生成不同的文本。

🌐 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.


press_sequentially

Added in: v1.38 locator.press_sequentially
tip

在大多数情况下,你应该改用 locator.fill()。只有在页面上有特殊的键盘处理时,你才需要逐个按键输入。

🌐 In most cases, you should use locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page.

聚焦该元素,然后对文本中的每个字符发送 keydownkeypress/inputkeyup 事件。

🌐 Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.

要按下特殊键,如 ControlArrowDown,请使用 locator.press()

🌐 To press a special key, like Control or ArrowDown, use locator.press().

用法

locator.press_sequentially("hello") # types instantly
locator.press_sequentially("world", delay=100) # types slower, like a user

在文本字段中输入内容然后提交表单的示例:

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

locator = page.get_by_label("Password")
locator.press_sequentially("my password")
locator.press("Enter")

参数

  • text str#

    要按顺序压入焦点元素的字符串。

  • delay float (optional)#

    按键之间的等待时间,以毫秒为单位。默认为 0。

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

返回


screenshot

Added in: v1.14 locator.screenshot

截取与定位器匹配的元素的屏幕截图。

🌐 Take a screenshot of the element matching the locator.

用法

page.get_by_role("link").screenshot()

禁用动画并将屏幕截图保存到文件中:

🌐 Disable animations and save screenshot to a file:

page.get_by_role("link").screenshot(animations="disabled", path="link.png")

参数

  • animations "disabled" | "allow" (optional)#

    当设置为 "disabled" 时,会停止 CSS 动画、CSS 过渡和 Web 动画。动画会根据其持续时间得到不同的处理:

    • 有限动画会被快进至完成,因此它们会触发 transitionend 事件。
    • 无限动画被取消到初始状态,然后在屏幕截图后播放。

    默认值为 "allow",不会改变动画。

  • caret "hide" | "initial" (optional)#

    当设置为 "hide" 时,截图将隐藏文本光标。当设置为 "initial" 时,文本光标的行为不会改变。默认值为 "hide"

  • mask List[Locator] (optional)#

    指定在截图时应被遮罩的定位器。被遮罩的元素将被一个粉色方框 #FF00FF 覆盖(可通过 mask_color 自定义),完全覆盖其边界框。遮罩也会应用到不可见元素,参见 仅匹配可见元素 可禁用此功能。

  • mask_color str (optional) Added in: v1.35#

    指定被遮罩元素的覆盖框颜色,使用 CSS 颜色格式。默认颜色是粉色 #FF00FF

  • omit_background bool (optional)#

    隐藏默认的白色背景,并允许捕获带透明度的截屏。不适用于 jpeg 图片。默认值为 false

  • path Union[str, pathlib.Path] (optional)#

    保存图片的文件路径。截图类型将根据文件扩展名来推断。如果path是相对路径,则相对于当前工作目录进行解析。如果未提供路径,则图片不会保存到磁盘上。

  • quality int (optional)#

    图片质量,范围为0-100。不适用于 png 图片。

  • scale "css" | "device" (optional)#

    当设置为 "css" 时,截图将每个页面的 CSS 像素对应一个像素。对于高分辨率设备,这将保持截图文件较小。使用 "device" 选项将每个设备像素对应一个像素,因此高分辨率设备的截图将会大两倍甚至更多。

    默认为 "device"

  • style str (optional) Added in: v1.41#

    在截图时要应用的样式表文本。在这里,你可以隐藏动态元素,使元素不可见或更改它们的属性,以帮助你创建可重复的截图。此样式表可以穿透 Shadow DOM 并应用于内部框架。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • type "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.


scroll_into_view_if_needed

Added in: v1.14 locator.scroll_into_view_if_needed

此方法会等待 actionability 检查,然后尝试将元素滚动到可见区域,除非它已经完全可见,如 IntersectionObserverratio 所定义。

🌐 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.

用法

locator.scroll_into_view_if_needed()
locator.scroll_into_view_if_needed(**kwargs)

参数

返回


select_option

Added in: v1.14 locator.select_option

<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
element.select_option("blue")
# single selection matching the label
element.select_option(label="blue")
# multiple selection for blue, red and second option
element.select_option(value=["red", "green", "blue"])

参数

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • element ElementHandle | List[ElementHandle] (optional)#

    要选择的选项元素。可选。

  • index int | List[int] (optional)#

    按索引选择的选项。可选。

  • value str | List[str] (optional)#

    按值选择的选项。如果 <select> 拥有 multiple 属性,则选择所有给定的选项,否则只选择第一个匹配传入选项的选项。可选。

  • label str | List[str] (optional)#

    按标签选择的选项。如果 <select> 拥有 multiple 属性,则选择所有给定的选项,否则只选择第一个匹配传入选项之一的选项。可选。

返回

详情

此方法会等待 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.

在所有提供的选项都被选择后,触发 changeinput 事件。

🌐 Triggers a change and input event once all the provided options have been selected.


select_text

Added in: v1.14 locator.select_text

该方法会等待可操作性检查,然后聚焦元素并选择其所有文本内容。

🌐 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.

用法

locator.select_text()
locator.select_text(**kwargs)

参数

返回


set_checked

Added in: v1.15 locator.set_checked

设置复选框或单选元素的状态。

🌐 Set the state of a checkbox or a radio element.

用法

page.get_by_role("checkbox").set_checked(True)

参数

  • checked bool#

    是否选中或取消选中复选框。

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • position Dict (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回

详情

此方法通过执行以下步骤来检查或取消选中元素:

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

  1. 确保匹配的元素是复选框或单选按钮。如果不是,该方法将抛出异常。
  2. 如果元素已经具有正确的检查状态,则此方法立即返回。
  3. 等待匹配元素的 可操作性 检查,除非设置了 强制 选项。如果元素在检查过程中被分离,整个操作将重试。
  4. 如果需要,将元素滚动到视图中。
  5. 使用 page.mouse 点击元素的中心。
  6. 确保该元素现在已被选中或未被选中。如果没有,则此方法会抛出异常。

当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。

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


set_input_files

Added in: v1.14 locator.set_input_files

将文件或多个文件上传到 <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
page.get_by_label("Upload file").set_input_files('myfile.pdf')

# Select multiple files
page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])

# Select a directory
page.get_by_label("Upload directory").set_input_files('mydir')

# Remove all the selected files
page.get_by_label("Upload file").set_input_files([])

# Upload buffer from memory
page.get_by_label("Upload file").set_input_files(
files=[
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
],
)

参数

返回

详情

将文件输入的值设置为这些文件路径或文件。如果某些 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.


tap

Added in: v1.14 locator.tap

在匹配定位器的元素上执行轻敲手势。有关通过手动分发触摸事件来模拟其他手势的示例,请参见模拟传统触摸事件页面。

🌐 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.

用法

locator.tap()
locator.tap(**kwargs)

参数

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • modifiers List["Alt" | "Control" | "ControlOrMeta" | "Meta" | "Shift"] (optional)#

    要按下的修饰键。确保在操作过程中仅按下这些修饰键,然后恢复当前的修饰键。如果未指定,则使用当前按下的修饰键。“ControlOrMeta”在 Windows 和 Linux 上对应“Control”,在 macOS 上对应“Meta”。

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • position Dict (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,此方法仅执行actionability 检查,而跳过实际操作。默认值为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。请注意,无论 trial 如何,键盘 modifiers 都会被按下,以便测试那些仅在按下这些键时才可见的元素。

返回

详情

此方法通过执行以下步骤来点击元素:

🌐 This method taps the element by performing the following steps:

  1. 等待对该元素的可操作性检查,除非设置了强制选项。
  2. 如果需要,将元素滚动到视图中。
  3. 使用 page.touchscreen 点击元素的中心,或指定的 位置

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。

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

note

element.tap() 要求将浏览器上下文的 hasTouch 选项设置为 true。


text_content

Added in: v1.14locator.text_content

返回 node.textContent

🌐 Returns the node.textContent.

Asserting text

如果你需要断言页面上的文本,建议使用 expect(locator).to_have_text() 以避免不稳定。更多详情请参见 断言指南

🌐 If you need to assert text on the page, prefer expect(locator).to_have_text() to avoid flakiness. See assertions guide for more details.

用法

locator.text_content()
locator.text_content(**kwargs)

参数

返回


uncheck

Added in: v1.14 locator.uncheck

确保复选框或单选元素未选中。

🌐 Ensure that checkbox or radio element is unchecked.

用法

page.get_by_role("checkbox").uncheck()

参数

  • force bool (optional)#

    是否绕过 可操作性 检查。默认值为 false

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • position Dict (optional)#

    相对于元素内边距盒左上角使用的一个点。如果未指定,则使用元素的某个可见点。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

  • trial bool (optional)#

    设置后,该方法仅执行 可操作性 检查,而跳过实际操作。默认为 false。在不执行操作的情况下,等待元素准备好进行操作时非常有用。

返回

详情

此方法通过执行以下步骤取消选中该元素:

🌐 This method unchecks the element by performing the following steps:

  1. 确保该元素是复选框或单选按钮输入。如果不是,该方法会抛出异常。如果元素已经未选中,该方法会立即返回。
  2. 等待对该元素的可操作性检查,除非设置了强制选项。
  3. 如果需要,将元素滚动到视图中。
  4. 使用 page.mouse 点击元素的中心。
  5. 确保该元素现在未被选中。如果不是,这种方法会抛出异常。

如果该元素在操作过程中的任何时刻与 DOM 分离,则此方法会抛出异常。

🌐 If the element is detached from the DOM at any moment during the action, this method throws.

当所有步骤在指定的超时内未完成时,该方法会抛出TimeoutError。传递零超时可禁用此功能。

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


wait_for

Added in: v1.16 locator.wait_for

当由定位器指定的元素满足 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.

用法

order_sent = page.locator("#order-sent")
order_sent.wait_for()

参数

  • state "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 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

返回


属性

🌐 Properties

content_frame

Added in: v1.43 locator.content_frame

返回一个 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.

对于反向操作,请使用 frame_locator.owner

🌐 For a reverse operation, use frame_locator.owner.

用法

locator = page.locator("iframe[name=\"embedded\"]")
# ...
frame_locator = locator.content_frame
frame_locator.get_by_role("button").click()

返回


description

Added in: v1.57 locator.description

返回先前使用 locator.describe() 设置的定位器描述。如果未设置自定义描述,则返回 null

🌐 Returns locator description previously set with locator.describe(). Returns null if no custom description has been set.

用法

button = page.get_by_role("button").describe("Subscribe button")
print(button.description()) # "Subscribe button"

input = page.get_by_role("textbox")
print(input.description()) # None

返回


first

Added in: v1.14 locator.first

返回第一个匹配元素的定位器。

🌐 Returns locator to the first matching element.

用法

locator.first

返回


last

Added in: v1.14 locator.last

返回最后一个匹配元素的定位器。

🌐 Returns locator to the last matching element.

用法

banana = page.get_by_role("listitem").last

返回


page

Added in: v1.19 locator.page

该定位器所属的页面。

🌐 A page this locator belongs to.

用法

locator.page

返回


已弃用

🌐 Deprecated

element_handle

Added in: v1.14 locator.element_handle
Discouraged

始终优先使用 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.

用法

locator.element_handle()
locator.element_handle(**kwargs)

参数

返回


element_handles

Added in: v1.14 locator.element_handles
Discouraged

始终优先使用 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.

用法

locator.element_handles()

返回


type

Added in: v1.14 locator.type
已弃用

在大多数情况下,你应该改用 locator.fill()。只有在页面上有特殊键盘处理时,才需要逐个按键,此时使用 locator.press_sequentially()

🌐 In most cases, you should use locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use locator.press_sequentially().

聚焦该元素,然后对文本中的每个字符发送 keydownkeypress/inputkeyup 事件。

🌐 Focuses the element, and then sends a keydown, keypress/input, and keyup event for each character in the text.

要按下特殊键,如 ControlArrowDown,请使用 locator.press()

🌐 To press a special key, like Control or ArrowDown, use locator.press().

用法

参数

  • text str#

    要输入到焦点元素中的文本。

  • delay float (optional)#

    按键之间的等待时间,以毫秒为单位。默认为 0。

  • no_wait_after bool (optional)#

    已弃用

    此选项无效。

    此选项无效。

  • timeout float (optional)#

    最长时间(以毫秒为单位)。默认值为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 browser_context.set_default_timeout()page.set_default_timeout() 方法进行更改。

返回