How to use relative xpath for locating a web-element by particular Attribute in Selenium?

SeleniumAutomation TestingTesting Tools

We can use relative xpath for locating web-element by particular attribute value. A relative xpath begins from the element to be located and not from the root.

It begins with the // symbol. It’s advantage is that even if an element is deleted or added in the DOM, the relative xpath for a specific element remains unaffected. To obtain a relative path by an attribute, the xpath expression is //tagname[@attribute='value'].

Let us identify the below highlighted element on the page with the help of the alt attribute.

Syntax

l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']")

Example

from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element with an attribute using xpath
l = driver.find_element_by_xpath("//img[@alt='tutorialspoint']")
#get src attribute
s = l.get_attribute('src')
print('Src attribute value is: ')
print(s)
#browser quit
driver.quit()

Output

raja
Published on 06-Apr-2021 08:30:41
Advertisements