英文:
Playwright selector for combining predicates
问题
li:has(div:text("6:00pm"):has(+div:text("Alpha"))) button
英文:
I need to find the button within the li that contains in its children both the text 6:00pm and the text Alpha.
<!-- language: 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>
...
I have
<!-- language: javascript -->
li:has(div:text("6:00pm")) button
which gives me both buttons for "6:00pm", but how to limit the selector to also match Alpha so I only get one button?
I basically need to add a conjunction to the predicate.
答案1
得分: 3
以下是代码的翻译部分:
You can combine filter calls to create a logical "and" of your conditions:
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"})
    .locator("button");
  console.log(await btn.textContent()); // => Do it!
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());
英文:
You can combine filter calls to create a logical "and" of your conditions:
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"})
    .locator("button");
  console.log(await btn.textContent()); // => Do it!
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论