typescript - 在 Playwright 中過濾類別和角色?
我想在 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!
});
我做錯了什麼?為什麼找不到連結?
答案#1
它無法找到該鏈接,因為定位器只搜尋已由 getByRole 找到的 <a> 元素的子元素。換句話說,它無法在它的子元素中找到自己。
如果我正確理解你的 HTML,:scope 偽選擇器應該可行,這基本上允許一個元素查詢自身以及它的子元素:
import {expect, test} from "@playwright/test"; // ^1.46.1
test("nav link has text 'hello world'", async ({page}) => {
const html = `<a class="navbar__brand" href="/">hello world</a>`;
await page.setContent(html); // for demonstration
const navLink = page
.getByRole("link")
.locator(":scope.navbar__brand"); // or ".navbar__brand:scope"
await expect(navLink).toHaveText("hello world");
});
當然,page.getByRole("a.navbar__brand") 是可行的,但作為網頁優先的選擇方法來說,不如單純按角色選擇來得好。不過,.navbar__brand 也不是網頁優先的方式,所以理想情況下,你會將所有條件合併成一次 page.getByRole("link", {name: "link text"}) 呼叫。
答案#2
你可以直接使用帶有 CSS 選擇器的定位器:
const links = page.locator("a.navbar__brand");
const count = await links.count();
console.log("count is " + count); // Should now output 1
