我需要在
button
中找到 li
,其子级中包含文本 6:00pm
和文本 Alpha
。
<li>
<div>6:00pm</div>
<div>Alpha</div>
<button>Do it!</button>
</li>
<li>
<div>6:00pm</div>
<div>Beta</div>
<button>Do it!</button>
</li>
...
我有
li:has(div:text("6:00pm")) button
这为我提供了“6:00pm”的两个
button
,但是如何限制选择器也匹配Alpha
,这样我就只能得到一个按钮?
我基本上需要在谓语中添加一个连词。
您可以组合
filter
调用来创建条件的逻辑“与”:
const playwright = require("playwright"); // ^1.30.0
const html = `<!DOCTYPE html>
<li>
<div>6:00pm</div>
<div>Alpha</div>
<button>Do it!</button>
</li>
<li>
<div>6:00pm</div>
<div>Beta</div>
<button>Do it!</button>
</li>`;
let browser;
(async () => {
browser = await playwright.chromium.launch();
const page = await browser.newPage();
await page.setContent(html);
const btn = page
.getByRole("listitem")
.filter({hasText: "Alpha"})
.filter({hasText: "6:00pm"})
.getByRole("button");
console.log(await btn.textContent()); // => Do it!
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
虽然这些不使用首选角色定位器并预设文本顺序,但以下也是可能的:
page.locator("li:text('6:00pm Alpha') button");
page.locator("li:has-text('6:00pm Alpha') button");