Tutorial 3 – Identify Nth element using Playwright Python
What you will Learn in this blog:
How to identify nth element using Playwright Python
Code snippets
How to identify nth element using Playwright python
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 text field is of the type ‘input’ tagname
Let us use the ‘input’ locator and fill the text field with some string:
So our code snippet looks like:
Save and execute
Notice the expected error below.
The playwright complains that it 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 convention.
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 all the 3 fields are populated and 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
Comment lines#10, 11, 12, 14
Save and execute.
Notice below that the last input field gets populated
Code snippet
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False,slow_mo=2000)
context = browser.new_context()
page = context.new_page()
page.goto("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("input >> nth=-1").fill("angular")
#page.locator("button").click()
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
Thank you for reading!