简体   繁体   中英

playwright equivalent of find() in cypress

Is there a way to traverse through html elements in playwright like cy.get("abc").find("div") in cypress?

In other words, any find() equivalent method in playwright?

page.locator("abc").find() is not a valid method in playwright though:(

If you assign the parent element handle to a variable, any of the findBy* functions (or locator ) will search only in the parent element. An example below where the parent is a div , the child is a button , and we use .locator() to find the elements.

test('foo', async ({ page }) => {
  await page.goto('/foo');
  const parent = await page.locator('div');
  const child = await parent.locator('button');
});

You can just combine the selectors, this will resolve to div below abc

page.locator("abc div")

Let's consider the website https://www.example.com with the following 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>

As mentioned by @agoff, you can use nested locator page.locator('p').locator('a') or you can specify the nested selector directly in the locator 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();
})();

Since you mentioned that you need to traverse through the HTML elements, elementHandles can be used to traverse through the elements specified by the locator as mentioned in the above code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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