【问题标题】:PlayWright - Selecting link with nth-match and value in hrefPlayWright - 选择第 n 次匹配的链接和 href 中的值
【发布时间】:2023-02-26 18:21:23
【问题描述】:

我有一个页面,我需要在其中选择一个链接。

页面上的链接是(例如):

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

我需要的链接是

  1. 第一个“预览结果”链接 和
  2. 第一个'ID=22222'

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

    await page.locator(':nth-match(a:has-text("Preview Results"), 1)').click();

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

【问题讨论】:

    标签: playwright


    【解决方案1】:

    这似乎是 CSS attribute selectors 的一个很好的用例:

    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());
    

    要考虑的几个变体:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2021-05-11
      • 2023-03-12
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多