Home > Enterprise >  Selenium Select to return a list?
Selenium Select to return a list?

Time:03-26

In python we have:

select = Select(driver.find_element_by_id('fruits01'))

But what if I want to have a list of all select tags and not just the first one?

I tried:

select = Select(driver.find_elements_by_id('fruits01'))

But it didn't work for me.

CodePudding user response:

As per the Selenium Python API Docs of Select():

class selenium.webdriver.support.select.Select(webelement)
    A check is made that the given element is, indeed, a SELECT tag. If it is not, then an UnexpectedTagNameException is thrown.

So Select() takes a webelement as an argument and you won't be able to pass webelements.

Moreover, each webelement is unique within the DOM Tree. So it's highly unlikely multiple elements would be identified using the same value of id attribute i.e. fruits01.


This usecase

However, considering the usecase as a valid usecase the simplest approach would be similar to @Arundeep Chohan's answer but ideally inducing WebDriverWait for the visibility_of_all_elements_located() as follows:

elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.ID, "fruits01")))
for element in elements:
    select = Select(element)

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

CodePudding user response:

elems=driver.find_elements_by_id('fruits01')
for elem in elems:
   select=Select(elem)

Why not just use a list to loop them ? I don't think you can do it the way you want to.

  • Related