Playwright选择器用于组合谓词。

huangapple go评论105阅读模式
英文:

Playwright selector for combining predicates

问题

  1. 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 -->

  1. &lt;li&gt;
  2. &lt;div&gt;6:00pm&lt;/div&gt;
  3. &lt;div&gt;Alpha&lt;/div&gt;
  4. &lt;button&gt;Do it!&lt;/button&gt;
  5. &lt;/li&gt;
  6. &lt;li&gt;
  7. &lt;div&gt;6:00pm&lt;/div&gt;
  8. &lt;div&gt;Beta&lt;/div&gt;
  9. &lt;button&gt;Do it!&lt;/button&gt;
  10. &lt;/li&gt;
  11. ...

I have

<!-- language: javascript -->

  1. li:has(div:text(&quot;6:00pm&quot;)) 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:

  1. const playwright = require("playwright"); // ^1.30.0
  2. const html = `<!DOCTYPE html>
  3. <li>
  4. <div>6:00pm</div>
  5. <div>Alpha</div>
  6. <button>Do it!</button>
  7. </li>
  8. <li>
  9. <div>6:00pm</div>
  10. <div>Beta</div>
  11. <button>Do it!</button>
  12. </li>`;
  13. let browser;
  14. (async () => {
  15. browser = await playwright.chromium.launch();
  16. const page = await browser.newPage();
  17. await page.setContent(html);
  18. const btn = page
  19. .getByRole("listitem")
  20. .filter({hasText: "Alpha"})
  21. .filter({hasText: "6:00pm"})
  22. .locator("button");
  23. console.log(await btn.textContent()); // => Do it!
  24. })()
  25. .catch(err => console.error(err))
  26. .finally(() => browser?.close());
英文:

You can combine filter calls to create a logical "and" of your conditions:

  1. const playwright = require(&quot;playwright&quot;); // ^1.30.0
  2. const html = `&lt;!DOCTYPE html&gt;
  3. &lt;li&gt;
  4. &lt;div&gt;6:00pm&lt;/div&gt;
  5. &lt;div&gt;Alpha&lt;/div&gt;
  6. &lt;button&gt;Do it!&lt;/button&gt;
  7. &lt;/li&gt;
  8. &lt;li&gt;
  9. &lt;div&gt;6:00pm&lt;/div&gt;
  10. &lt;div&gt;Beta&lt;/div&gt;
  11. &lt;button&gt;Do it!&lt;/button&gt;
  12. &lt;/li&gt;`;
  13. let browser;
  14. (async () =&gt; {
  15. browser = await playwright.chromium.launch();
  16. const page = await browser.newPage();
  17. await page.setContent(html);
  18. const btn = page
  19. .getByRole(&quot;listitem&quot;)
  20. .filter({hasText: &quot;Alpha&quot;})
  21. .filter({hasText: &quot;6:00pm&quot;})
  22. .locator(&quot;button&quot;);
  23. console.log(await btn.textContent()); // =&gt; Do it!
  24. })()
  25. .catch(err =&gt; console.error(err))
  26. .finally(() =&gt; browser?.close());

huangapple
  • 本文由 发表于 2023年2月23日 20:05:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定