繁体   English   中英

相当于 cypress 中的 find() 的剧作家

[英]playwright equivalent of find() in cypress

有没有办法像cypress中的cy.get("abc").find("div")一样遍历playwright中的html个元素?

换句话说,剧作家中有任何find()等效方法吗?

page.locator("abc").find()在剧作家中不是一个有效的方法:(

如果将父元素句柄分配给变量,则任何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');
});

您可以组合选择器,这将解析为abc下面的div

page.locator("abc div")

让我们考虑网站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来遍历locator指定的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM