How to select element using XPATH syntax on Selenium for Python?


We can select elements using xpath with Selenium webdriver. Xpath is one of the most important locators. There are two types of xpath. They are known as absolute [starting from parent node in DOM] and relative xpath [starting from anywhere in DOM].

The xpath syntax is − //tagname[@attribute='value'] or //*[@attribute='value'].

Let us consider the html code of an element that we shall identify with the help of xpath−

The xpath expression is //input[@name='firstname'] or //*[@name='firstname'].

Example

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
// identify element with xpath
l = driver.find_element_by_xpath("//input[@name='firstname']")
l.send_keys("Python")
driver.quit()

Output

Updated on: 18-Sep-2020

890 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements