跳转到主要内容

句柄

简介

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

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

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

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

API 参考

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

const jsHandle = await page.evaluateHandle('window');
// Use jsHandle for evaluations.

元素句柄

不推荐

不鼓励使用 ElementHandle,请改用 Locator 对象和 web-first 断言。

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

// Get the element handle
const elementHandle = page.waitForSelector('#box');

// Assert bounding box for the element
const boundingBox = await elementHandle.boundingBox();
expect(boundingBox.width).toBe(100);

// Assert attribute for the element
const classNames = await elementHandle.getAttribute('class');
expect(classNames.includes('highlighted')).toBeTruthy();

作为参数的句柄

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

// Create new array in page.
const myArrayHandle = await page.evaluateHandle(() => {
window.myArray = [1];
return myArray;
});

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

// Add one more element to the array using the handle
await page.evaluate(arg => arg.myArray.push(arg.newElement), {
myArray: myArrayHandle,
newElement: 2
});

// Release the object when it's no longer needed.
await myArrayHandle.dispose();

句柄生命周期

可以使用页面方法(例如 page.evaluateHandle()page.$()page.$$())或其框架对应方法(frame.evaluateHandle()frame.$()frame.$$())获取句柄。一旦创建,除非页面导航或句柄通过 jsHandle.dispose() 方法手动处置,否则句柄将保留对象以避免 垃圾回收

API 参考

Locator vs ElementHandle

注意

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

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

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

const handle = await page.$('text=Submit');
// ...
await handle.hover();
await handle.click();

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

const locator = page.getByText('Submit');
// ...
await locator.hover();
await locator.click();