Is there a way to find an element by attributes in Python Selenium?

SeleniumAutomation TestingTesting Tools

We can find an element by attributes with Selenium webdriver. There are multiple ways to do this. We can use the locators like css and xpath that use attributes and its value to identify an element.

For css selector, theexpression to be used is tagname[attribute='value']. There are two types of xpath – absolute and relative. The xpath expression to be used is //tagname[@attribute='value'], the tagname in the expression is optional. If omitted, the xpath expression should be //*[@attribute='value'].

Let us consider an element with input tagname. It will be identified with xpath locator with id attribute (//input[@id='txtSearchText']).

Example

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
#identify element with attribute id
l= driver.find_element_by_xpath("//input[@id='txtSearchText']")
l.send_keys("Tutorialspoint")
#get_attribute() to get value of input box
print("Enter text is: " + l.get_attribute('value'))
driver.close()

Output

raja
Published on 18-Sep-2020 15:49:29
Advertisements