UnexpectedTagNameException: Message: Select only works on <select> elements, not on <li>error selecting li element from a Dropdown using Selenium

Viewed 5099

I wish to click on New Test. The HTML code looks something like this. I'm new here and beginning to learn automation using selenium-python.

<li id="testing">

<ul class="dd">
    <li><a href="javascript:toolsPopup('/abc/xyz/text.html');"><span>New Test</span></a></li>
    <li><a href="javascript:toolsPopup('/abc/xyz/list.html');"><span>Test List</span></a></li>
</ul>
</li>

The code that I'm trying to use

element=driver.find_element_by_id('testing')
drp=Select(element)
drp.select_by_visible_text('New Test')

But getting the error

selenium.common.exceptions.UnexpectedTagNameException: Message: Select only works on <select> elements, not on <li> 

Any help would be highly appreciated. Thanks!

2 Answers

As dropdown element with text as New Test is not with in a Select node you can't use Select class. To select <option> with text as New Test you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following based Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li#testing > ul.dd li > a[href*='/abc/xyz/text.html'] > span"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//li[@id='testing']/ul[@class='dd']//li/a/span[text()='New Test']"))).click()
    
  • Note : You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Reference

You can find a couple of relevant discussions in:

The Select method works only for dropdowns which has HTML tag select. In your case you can not use a select method, just write locator( XPath, CSS, or else) for the element which you want to detect from the dropdown.

In your case the XPath of the element which you wanted should be:

//li[text()='New Test']
Related