1

I'm using the Selenium Kit in Python and am trying to select an option from a drop-down menu.

For this I'm using python driver.select_by_visible_text() . My problem is now that the visible text always contains the value I'm looking but with something added afterwards. The select_by_visible_text() just finds the exact option, but I can´t name it exactly.

For example: I'm looking for the option "W33", the website then says "W33 (only 4 left)". I would like to select "W33 (only 4 left)", but don´t know how to achieve this?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
N4MeD
  • 13
  • 1
  • 4

2 Answers2

0

As the static part of the visible text i.e. W33 is always followed by a variable text, e.g. (only 4 left), (only 3 left), etc, so select_by_visible_text() may not be effective. You may have to consider either among:


Alternative

As an alternative you can also use the based Locator Strategy as follows:

driver.find_element_by_xpath("//select//option[contains(., 'W33')]").click()

Note: You may need to expand the <select> element first before clicking on the option.

Ideally, you need to induce WebDriverWait for the element_to_be_clickable() as follows:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select//option[contains(., 'W33')]"))).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 relevant discussion in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
-1

You can get a list of all options with the options attribute on your Select object:

from selenium.webdriver.support.ui import Select

elem = driver.find_element_by_id('myselect')
elem_select = Select(elem)
opts = elem_select.options

Then, check which of them matches. In your example, check the text attribute:

opts_to_select = [o for o in opts if o.text.startswith('W33')]
my_option = opts_to_select[0] # select first match
                              # (Maybe you also want to raise an error if 
                              # there is more than one match.)

And select it:

if not my_elem.is_selected():
    my_elem.click()

Source: Select at selenium-python documentation

Rve
  • 380
  • 4
  • 6
  • Why was this downvoted, is there something wrong? It answers the question and is accepted. – Rve Nov 19 '20 at 20:32