How to identify nth element using xpath in Selenium with python?


There are multiple ways of building a customized xpath. In case we need to identify nth element we can achieve this by the ways listed below.

  • position() method in xpath.

    Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1.

Syntax

driver.find_element_by_xpath("//input[@type='text'][position()=1]")
  • square bracket addition with braces to indicate index.

    Suppose we need to reach the third row of the table and the customized xpath for that row should be indicated with the help of [3] expression.

Syntax

driver.find_element_by_xpath("//table/tbody/tr[2]/td[2]")

Example

Code Implementation with position()

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of position()
driver.find_element_by_xpath("//input[@type='text'][position()=1]").
send_keys("Selenium")
#to close the browser
driver.close()

Code Implementation with index

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm")
#to refresh the browser
driver.refresh()
# printing the first data in the row 2 of table with index
print(driver.find_element_by_xpath("//table/tbody/tr[2]/td[1]").text)
#to close the browser
driver.close()

Updated on: 29-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements