Playwright中怎么判断元素是否存在?

766 阅读1分钟

前言

Playwright 中,判断元素是否存在是一个非常常见的场景,我们可以使用locator.isVisible()locator.count() 来实现,我们一起来看看具体代码吧。

使用 locator.isVisible()

locator.isVisible()可以检查元素是否可见,如果元素存在且可见,返回 true,否则返回 false

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');

  const locator = page.locator('selector-of-element');
  const isVisible = await locator.isVisible();
  console.log(isVisible); // 输出true或false

  await browser.close();
})();

在这段代码中,我们使用 page.locator('selector-of-element') 获取了元素后,然后又使用 isVisible()进行了判断,非常方便。

使用 locator.count()

通过 locator.count() 来获取页面上匹配元素的数量。如果数量大于 0,表示元素存在;否则元素不存在。

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');

  const locator = page.locator('selector-of-element');
  const count = await locator.count();
  if (count > 0) {
    console.log('元素存在');
  } else {
    console.log('元素不存在');
  }

  await browser.close();
})();

这两种方法都可以有效地检查元素是否存在,实际开发中,你可以根据你的需求选择合适的方式。