跳至主要内容

句柄

简介

Playwright 可以创建对页面 DOM 元素或页面内任何其他对象的句柄。这些句柄存在于 Playwright 进程中,而实际对象则存在于浏览器中。有两种类型的句柄:

  • JSHandle 用于引用页面中的任何JavaScript对象
  • ElementHandle 用于引用页面中的DOM元素,它具有额外的方法,允许对元素执行操作并断言其属性。

由于页面中的任何DOM元素也是一个JavaScript对象,因此任何ElementHandle同时也是一个JSHandle

句柄用于对页面中的实际对象执行操作。您可以在句柄上进行求值、获取句柄属性、将句柄作为求值参数传递、将页面对象序列化为JSON等。有关这些操作和方法,请参见JSHandle类API。

API参考

这是获取JSHandle最简单的方法。

js_handle = page.evaluate_handle('window')
# Use jsHandle for evaluations.

元素句柄

Discouraged

不建议使用ElementHandle,请改用Locator对象和面向网页的断言。

当需要ElementHandle时,建议使用page.wait_for_selector()frame.wait_for_selector()方法来获取它。这些API会等待元素被附加并可见。

# Get the element handle
element_handle = page.wait_for_selector('#box')

# Assert bounding box for the element
bounding_box = element_handle.bounding_box()
assert bounding_box.width == 100

# Assert attribute for the element
class_names = element_handle.get_attribute('class')
assert 'highlighted' in class_names

将句柄作为参数

句柄可以传入page.evaluate()及类似方法中。以下代码片段在页面中创建一个新数组,用数据初始化它,并将该数组的句柄返回给Playwright。随后在后续评估中使用该句柄:

# Create new array in page.
my_array_handle = page.evaluate_handle("""() => {
window.myArray = [1];
return myArray;
}""")

# Get current length of the array.
length = page.evaluate("a => a.length", my_array_handle)

# Add one more element to the array using the handle
page.evaluate("(arg) => arg.myArray.push(arg.newElement)", {
'myArray': my_array_handle,
'newElement': 2
})

# Release the object when it's no longer needed.
my_array_handle.dispose()

处理生命周期

可以通过页面方法获取句柄,例如page.evaluate_handle()page.query_selector()page.query_selector_all(),或者它们对应的框架方法frame.evaluate_handle()frame.query_selector()frame.query_selector_all()。一旦创建,句柄将保留对象不被垃圾回收,除非页面导航或通过js_handle.dispose()方法手动释放句柄。

API参考

定位器 vs 元素句柄

caution

我们仅建议在极少数需要对静态页面进行大量DOM遍历的情况下使用ElementHandle。对于所有用户操作和断言,请改用定位器。

LocatorElementHandle的区别在于,后者指向特定元素,而Locator则封装了如何检索该元素的逻辑。

在下面的示例中,handle指向页面上的特定DOM元素。如果该元素更改了文本或被React用来渲染完全不同的组件,handle仍然指向那个过时的DOM元素。这可能会导致意外行为。

handle = page.query_selector("text=Submit")
handle.hover()
handle.click()

使用定位器时,每次使用该定位器都会在页面中使用选择器查找最新的DOM元素。因此,在下面的代码片段中,底层DOM元素将被定位两次。

locator = page.get_by_text("Submit")
locator.hover()
locator.click()