Home > database >  Problem in selecting a drop-down list with Selenium using Python
Problem in selecting a drop-down list with Selenium using Python

Time:06-15

Here is my example

<select name="ptype"  onchange="if(this.value==99){jQuery('#ptypeDescSpan').show();}else{jQuery('#ptypeDescSpan').hide();}" id="ptype">
  <option value="">---</option>
  <option value="1">op1</option>
  <option value="2">op2</option>
  <option value="3">op3</option>
  <option value="99">other</option>
</select>
<span id="ptypeDescSpan" style="display: none">
  <input type="text" name="ptypeDesc" text="true"  value="" id="ptypeDesc">
</span> 

I want to select "other". Here is my code.

elem1 = driver.find_element_by_id('ptype')
select1 = Select(elem)
select1.select_by_value('99')

After running the codes, I find out... "No errors occured but nothing was selected"

First I checked the texts from each options, it showed correct results.

for i in select1.options:
    print(i.text)

Output was --- op1 op2 op3 other

I tried

driver.find_element_by_css_selector('#ptype > option:nth-child(5)').click()

But still, no errors occured but nothing was selected Any suggestions?

CodePudding user response:

You can use the below to select the value:

el = driver.find_element_by_id('id_of_select')
for option in el.find_elements_by_tag_name('option'):
    if option.text == 'The Options I Am Looking For':
        option.click() # select() in earlier versions of webdriver
        break

OR

element= WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.ID, "Correct_ID_Element")))
actionChains = ActionChains(driver)
actionChains.move_to_element(element).perform()
select = Select(element)
select.select_by_visible_text('other')

Import

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

OR you can enhance this like below

element= WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.ID, "drop_down_ID")))
actionChains = ActionChains(driver)
actionChains.move_to_element(element).perform()
select = Select(element)
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "xpath_of_locator")))
select.select_by_visible_text('other')
  • Related