Identify Nth element using Playwright Java

Tutorial 20​​ ​​ Identify Nth element​​ using​​ Playwright​​ Java​​ 

What you will Learn​​ in this​​ blog:

  • How to identify nth elementusing Playwright Java

  • Code snippets

How to identify nth element​​ using PW

Launch

https://www.way2automation.com/angularjs-protractor/registeration/#/login​​ ​​ 

Notice below that there are 3 text fields

Inspect any of the text field, notice that the field of type ‘input’ tagname

Let us use the ‘input’ locator and fill the text field with some string:

So our code looks like:

Save and execute.

Notice the expected error below. The error means that playwright has found 3 input fields and is unable to decide which input field it should consider

So how do we instruct playwright to select the first input field?

We can use the below reference. The first field has index 0, second has index​​ 1 ​​​​ and so on…

We can now use ‘nth element’ syntax

Save and execute.

Notice below that ‘angular’ gets typed in first text field

Let us change the index to 2

Save and execute.

Notice below that ‘angular’ gets typed in last text field

Let us now use nth element approach to fill all the 3 fields

Save and execute.​​ 

Notice below that we are logged in

We can also use negative index numbers. The last field will have the index -1 and so on….

Let us try with -1

 

Code snippet

package​​ com.w2a.pwjava;

 

import​​ com.microsoft.playwright.Browser;

import​​ com.microsoft.playwright.BrowserContext;

import​​ com.microsoft.playwright.BrowserType;

import​​ com.microsoft.playwright.Page;

import​​ com.microsoft.playwright.Playwright;

 

public​​ class​​ NthElementPW {

public​​ static​​ void​​ main(String[]​​ args)​​ throws​​ InterruptedException {

 Playwright​​ pw​​ = Playwright.create();

 Browser​​ browser​​ =​​ pw.chromium().launch(new​​ BrowserType.LaunchOptions().setHeadless(false));

 

 BrowserContext​​ browserContext​​ =​​ browser.newContext();

 Page​​ page​​ =​​ browserContext.newPage();

page.navigate("https://www.way2automation.com/angularjs-protractor/registeration/#/login");

page.locator("input >> nth=0").fill("angular");

page.locator("input >> nth=1").fill("password");

page.locator("input >> nth=2").fill("angular");

page.locator("button").click();

//page.locator("input >> nth=-1").fill("angular");

 }

 

}

 

Thank you for reading!

Share On

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on tumblr
Share on email

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Lifetime Membership Club

LIFETIME MEMBERSHIP BIG SALE - ALL LIVE COURES JUST - 7000 RS/ 99 USD
Attend All Live courses in just 7000 rs / $99 - offer ends 10th Nov 2024