user3788728
user3788728

Reputation: 59

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.

Upvotes: 3

Views: 10898

Answers (3)

Deepak M
Deepak M

Reputation: 11

theMenu = self.browser.find_element_by_link_text('Title of Menu')
theMenu.click()
menuItem = self.browser.find_element_by_link_text('Title of Menu Item')
menuItem.click()

Upvotes: 0

Yi Zeng
Yi Zeng

Reputation: 32895

After inspecting the DOM of that website, <select id="selectbox" name="focus" style="display: none;"> isn't the one people see in the UI.

The actual drop-down menu is:

<div id="selectbox_container" class="selectbox-wrapper" style="display: none; width: 150px;">
   <ul>
      <li id="selectbox_input_product" class="selected">Product Name or Number</li>
      <li id="selectbox_input_cas">CAS Number</li>
      <li id="selectbox_input_mdl">MDL Number</li>
      <li id="selectbox_input_msds">MSDS</li>
      <li id="selectbox_input_cofa">Certificate of Analysis</li>
      <li id="selectbox_input_formula">Molecular Formula</li>
      <li id="selectbox_input_keyword">Keyword</li>
   </ul>
</div>

Hence please give the following code a try:

driver = webdriver.Chrome()
driver.get("http://www.strem.com/")

driver.find_element_by_id("selectbox_input").click()
driver.find_element_by_id("selectbox_input_cas").click()

Upvotes: 3

alecxe
alecxe

Reputation: 474211

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.

Upvotes: 2

Related Questions