user3788728 user3788728 - 6 months ago 37
Python Question

python selenium select from drop-down menu

I am trying to select the "CAS Number" option on this website. From reading other posts, I have written several Python code using Selenium

driver.find_element_by_css_selector("select#selectbox > option[value='cas']").click()

driver.find_element_by_xpath("//select[@id ='selectbox']/option[@value ='cas']").click()

box = driver.find_element_by_id('selectbox')
for option in box.find_elements_by_tag_name('option'):
if option.text == 'cas':
option.select()


But they all fail to select the appropriate box. So I am wondering where the problem is.

Answer

First click on the input, then click the list item you need. Example, for CAS Number:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.strem.com')

element = driver.find_element_by_id('selectbox_input')
element.click()

li = driver.find_element_by_id('selectbox_input_cas')
li.click()

Note that it is not a regular select tag that could be much easier operated with using selenium.webdriver.support.select.Select.