typescript 筛选剧作家中的类和角色?

jc3wubiy  于 2022-12-14  发布在  TypeScript
关注(0)|答案(1)|浏览(116)

我想在Playwright网站上筛选一个包含navbar__brand类的链接-通过Playwright:

我的代码:

test("homepage has title and links to intro page", async ({ page }) => {
  await page.goto("https://playwright.dev/");

  const links = page.getByRole("link").locator(".navbar__brand");

  const count = await links.count();
  console.log("count is " + count); // zero instead of the expected one!
});

我做错了什么?为什么它找不到链接?

iqxoj9l9

iqxoj9l91#

它没有找到链接,因为定位器只搜索<a>元素的子元素,而getByRole元素已经找到了这个子元素,换句话说,它不能在它的子元素中找到自己。
如果我对HTML的理解正确的话,:scope伪选择器应该可以工作,它基本上允许元素查询自身及其子元素:

const playwright = require("playwright"); // ^1.28.1

const html = `<a class="navbar__brand" href="/">hello world</a>`;

let browser;
(async () => {
  browser = await playwright.chromium.launch();
  const page = await browser.newPage();
  await page.setContent(html);
  const result = await page.getByRole("link")
    .locator(":scope.navbar__brand") // or ".navbar__brand:scope"
    .textContent();
  console.log(result); // => hello world
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

相关问题