user16391157
user16391157

Reputation: 33

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

Upvotes: 3

Views: 2381

Answers (3)

Kartoos
Kartoos

Reputation: 1160

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.

Upvotes: 0

Blunt
Blunt

Reputation: 211

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

page.locator("abc div")

Upvotes: 4

agoff
agoff

Reputation: 7125

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');
});

Upvotes: 3

Related Questions