Playwright选择器用于组合谓词。

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

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

&lt;li&gt;
  &lt;div&gt;6:00pm&lt;/div&gt;
  &lt;div&gt;Alpha&lt;/div&gt;
  &lt;button&gt;Do it!&lt;/button&gt;
&lt;/li&gt;
&lt;li&gt;
  &lt;div&gt;6:00pm&lt;/div&gt;
  &lt;div&gt;Beta&lt;/div&gt;
  &lt;button&gt;Do it!&lt;/button&gt;
&lt;/li&gt;
...

I have

<!-- language: javascript -->

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:

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(&quot;playwright&quot;); // ^1.30.0

const html = `&lt;!DOCTYPE html&gt;
&lt;li&gt;
  &lt;div&gt;6:00pm&lt;/div&gt;
  &lt;div&gt;Alpha&lt;/div&gt;
  &lt;button&gt;Do it!&lt;/button&gt;
&lt;/li&gt;
&lt;li&gt;
  &lt;div&gt;6:00pm&lt;/div&gt;
  &lt;div&gt;Beta&lt;/div&gt;
  &lt;button&gt;Do it!&lt;/button&gt;
&lt;/li&gt;`;

let browser;
(async () =&gt; {
  browser = await playwright.chromium.launch();
  const page = await browser.newPage();
  await page.setContent(html);
  const btn = page
    .getByRole(&quot;listitem&quot;)
    .filter({hasText: &quot;Alpha&quot;})
    .filter({hasText: &quot;6:00pm&quot;})
    .locator(&quot;button&quot;);
  console.log(await btn.textContent()); // =&gt; Do it!
})()
  .catch(err =&gt; console.error(err))
  .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:

确定