跳转到主要内容

句柄

简介

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

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

由于页面上的任何 DOM 元素也是 JavaScript 对象,因此任何 ElementHandle 也是 JSHandle

句柄用于在页面上对这些实际对象执行操作。您可以评估句柄、获取句柄属性、将句柄作为评估参数传递、将页面对象序列化为 JSON 等。有关这些方法以及更多方法,请参阅 JSHandle 类 API。

API 参考

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

JSHandle jsHandle = page.evaluateHandle("window");
// Use jsHandle for evaluations.

元素句柄

不推荐

不推荐使用 ElementHandle,请改用 Locator 对象和 Web 优先断言。

当需要 ElementHandle 时,建议使用 Page.waitForSelector()Frame.waitForSelector() 方法获取它。这些 API 会等待元素附加和可见。

// Get the element handle
JSHandle jsHandle = page.waitForSelector("#box");
ElementHandle elementHandle = jsHandle.asElement();

// Assert bounding box for the element
BoundingBox boundingBox = elementHandle.boundingBox();
assertEquals(100, boundingBox.width);

// Assert attribute for the element
String classNames = elementHandle.getAttribute("class");
assertTrue(classNames.contains("highlighted"));

作为参数的句柄

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

// Create new array in page.
JSHandle myArrayHandle = page.evaluateHandle("() => {\n" +
" window.myArray = [1];\n" +
" return myArray;\n" +
"}");

// Get the length of the array.
int length = (int) page.evaluate("a => a.length", myArrayHandle);

// Add one more element to the array using the handle
Map<String, Object> arg = new HashMap<>();
arg.put("myArray", myArrayHandle);
arg.put("newElement", 2);
page.evaluate("arg => arg.myArray.add(arg.newElement)", arg);

// Release the object when it is no longer needed.
myArrayHandle.dispose();

句柄生命周期

可以使用 Page 方法(如 Page.evaluateHandle()Page.querySelector()Page.querySelectorAll())或它们的 Frame 对等方法(Frame.evaluateHandle()Frame.querySelector()Frame.querySelectorAll())来获取句柄。创建后,句柄将保留对象,直到页面导航或句柄通过 JSHandle.dispose() 方法手动释放,否则不会被 垃圾回收

API 参考

Locator vs ElementHandle

注意

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

LocatorElementHandle 之间的区别在于,后者指向一个特定元素,而 Locator 捕获检索该元素的方法。

在下面的示例中,句柄指向页面上的一个特定 DOM 元素。如果该元素的文本发生变化或被 React 用于渲染一个完全不同的组件,句柄仍然指向那个陈旧的 DOM 元素。这可能会导致意外行为。

ElementHandle handle = page.querySelector("text=Submit");
handle.hover();
handle.click();

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

Locator locator = page.getByText("Submit");
locator.hover();
locator.click();