
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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()
Advertisements