用于组合谓词的剧作家选择器

问题描述 投票:0回答:1

我需要在

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
,这样我就只能得到一个按钮?

我基本上需要在谓语中添加一个连词。

css-selectors playwright
1个回答
3
投票

您可以组合

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");
© www.soinside.com 2019 - 2024. All rights reserved.