Playwright中类似于Cypress中find()函数的等效函数是什么?

3
有没有类似于 Cypress 中的 cy.get("abc").find("div") 的方法可以在 playwright 中遍历 HTML 元素?
换句话说,playwright 中有没有任何等效于 find() 的方法?
尽管 page.locator("abc").find() 在 playwright 中不是一个有效的方法 :(

根据cypress文档所述,它似乎试图查找给定选择器的后代。您需要这样吗?还是有其他特定的用例? - Kartoos
在Playwright中需要与该功能相同的函数,可以遍历HTML元素。我们有类似的东西吗? - user16391157
3个回答

4
如果你将父元素的句柄分配给一个变量,那么任何findBy*函数(或locator)都只会在父元素中进行搜索。下面是一个例子,其中父元素是一个div,子元素是一个button,我们使用.locator()来找到这些元素。
test('foo', async ({ page }) => {
  await page.goto('/foo');
  const parent = await page.locator('div');
  const child = await parent.locator('button');
});

2
您可以组合选择器,这将解析为abc下面的div
page.locator("abc div")

1

让我们考虑以下网站https://www.example.com,其HTML代码如下:

<body style="">
  <div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p>
      <a href="https://www.iana.org/domains/example">More information...</a>
    </p>
  </div>
</body>

正如 @agoff 所提到的,您可以使用嵌套定位器 page.locator('p').locator('a') 或者直接在定位器中指定嵌套选择器 page.locator('p >> a')

// @ts-check
const playwright = require('playwright');

(async () => {
  const browser = await playwright.webkit.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://www.example.com/');

  // Here res1 and res2 produces same output
  const res1 = await page.locator('p').locator('a'); // nested locator
  const res2 = await page.locator('p >> a'); // directly specifying the selector to check the nested elements
  const out1 = await res1.innerText();
  const out2 = await res2.innerText();
  console.log(out1 == out2); // output: true
  console.log(out1); // output: More information...
  console.log(out2); // output: More information...

  // Traversal
  const result = await page.locator('p');
  const elementList = await result.elementHandles(); // elementList will contain list of <p> tags
  for (const element of elementList)
  {
    const out = await element.innerText()
    console.log(out);
  }
  // The above will output both the <p> tags' innerText i.e
  // This domain is for use in illustrative examples in...
  // More information...

  await browser.close();
})();

既然您提到需要遍历HTML元素,elementHandles可以用于遍历由定位器指定的元素,如上述代码所述。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接