Playwright - 选择第 n 个匹配项和 href 中的值的链接

dog*_*war 1 javascript playwright

我有一个页面,我需要在其中选择一个链接。页面上的链接是(例如):

<a href="/animation?ID=11111\&amp;model\_id=AAAAA">Preview Results</a>
<a href="/animation?ID=11111\&amp;model\_id=BBBBB">Preview Results</a>
<a href="/animation?ID=22222\&amp;model\_id=CCCCC">Preview Results</a>
<a href="/animation?ID=22222\&amp;model\_id=DDDDD">Preview Results</a>
<a href="/animation?ID=33333\&amp;model\_id=EEEEE">Preview Results</a>
<a href="/animation?ID=33333\&amp;model\_id=FFFFF">Preview Results</a>
Run Code Online (Sandbox Code Playgroud)

我需要的链接是第一个实例ID=22222

我可以获得第一个预览结果链接:

<a href="/animation?ID=11111\&amp;model\_id=AAAAA">Preview Results</a>
<a href="/animation?ID=11111\&amp;model\_id=BBBBB">Preview Results</a>
<a href="/animation?ID=22222\&amp;model\_id=CCCCC">Preview Results</a>
<a href="/animation?ID=22222\&amp;model\_id=DDDDD">Preview Results</a>
<a href="/animation?ID=33333\&amp;model\_id=EEEEE">Preview Results</a>
<a href="/animation?ID=33333\&amp;model\_id=FFFFF">Preview Results</a>
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能获得第一个ID链接(ID 22222)?

ggo*_*len 5

这似乎是CSS 属性选择器的一个很好的用例:

const playwright = require("playwright"); // ^1.30.1

const html = `<!DOCTYPE html>
<a href="/animation?ID=11111\&amp;model\_id=AAAAA">Preview Results</a>
<a href="/animation?ID=11111\&amp;model\_id=BBBBB">Preview Results</a>
<a href="/animation?ID=22222\&amp;model\_id=CCCCC">Preview Results</a>
<a href="/animation?ID=22222\&amp;model\_id=DDDDD">Preview Results</a>
<a href="/animation?ID=33333\&amp;model\_id=EEEEE">Preview Results</a>
<a href="/animation?ID=33333\&amp;model\_id=FFFFF">Preview Results</a>`;

let browser;
(async () => {
  browser = await playwright.chromium.launch();
  const page = await browser.newPage();
  await page.setContent(html);
  const loc = page.locator('[href*="ID=22222"]');
  console.log(await loc.first().getAttribute("href"));
    // => /animation?ID=22222&model_id=CCCCC
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());
Run Code Online (Sandbox Code Playgroud)

需要考虑的几个变体:

page.locator('[href*="ID=22222"]', {hasText: "Preview Results"});
Run Code Online (Sandbox Code Playgroud)
page.locator('[href*="ID=22222"][href*="id=CCCCC"]');
Run Code Online (Sandbox Code Playgroud)