Home > Software design >  Drop down option selection in selenium python
Drop down option selection in selenium python

Time:10-02

<select id="PRMT_SV_N0x29a524c0x0x2c68e47c_NS_" class="clsSelectControl pv" aria- 
 multiselectable="false" aria-invalid="false" style="width: 5cm;" xpath="1">

<option value="1" 
 dv="Transactions Only">&nbsp;Transactions&nbsp;Only</option>

<option 
 value="2" dv="Few Transactions Only">&nbsp;Transactions&nbsp;Only</option><option value="3" 
 dv="All Transactions">All&nbsp;Transactions</option>

</select>

I have HTML as above and it is drop down list. I have to click on element so I can see all three options and pick last option Value =3. Below is the code I have and it's not working or throwing any error. It's work to the part by clicking the element, but is not selecting the option.

 driver.find_element_by_xpath('/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/div[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/div[4]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/select[1]').click()

select = Select(driver.find_element_by_xpath('/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/div[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/div[4]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/select[1]'))
select.select_by_value('3')

CodePudding user response:

To select an element from a html-select menu you have to use the select Class and no need to click on element to select the drop-down value.

Code:

select= Select(driver.find_element_by_xpath('//select[contains(@class,'clsSelectControl')]'))
select.select_by_value(3)

Imports:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select

CodePudding user response:

Sometime Select class do not work properly, in those cases we would need JS intervention.

Please try this :

index = '3'
driver.execute_script(f"return document.querySelector('select.clsSelectControl.pv').selectedIndex = {index}")
  • Related