Python + Selenium | How to locate elements in span class & not unique ID


We can locate elements in span class and not unique id with the help of the Selenium webdriver. We can identify an element having a class attribute with the help of the locator xpath, css or class name.

To locate elements with these locators we have to use the By.xpath, By.xpath or By.cssSelector method. Then pass the locator value as a parameter to this method.

Let us see the html code of a button having a span class and try to identify it.

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/index.htm")
l = driver.find_element_by_id("textemail")
l.send_keys("abc@gmail.com")
#get value entered
s = l.get_attribute('value')
#identify element with span class
m = driver.find_element_by_xpath("//span[@class='input_group_button']")
#verify if element present
b = m.is_displayed()
if b:
   print("Element with span class available")
else:
   print("Element with span class not available")
#close browser
driver.close()

Output

Updated on: 08-Apr-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements