Search code examples
pythonhtmltestingsplinter

Can I somehow select a specific element from dropdown list on the page via splinter module in Python


Can I somehow select a specific element from dropdown list on the page via splinter module in Python?

I have the following HTML code:

<select id="xyz">
   <optgroup label="Group1">
      <option value="1">pick1</option>
      <option value="2">pick2</option>
   </optgroup>
   <optgroup label="Group2">
       <option value="3">pick3</option>
       <option value="4">pick4</option>
   </optgroup>
</select>

Suppose that I need to select "pick3" option. How can I do it?


Solution

  • First find the select element using find_by_id() and use select() method to select an option:

    element = browser.find_by_id('xyz').first
    element.select('3')
    

    Alternative solution would be to use find_by_xpath() and click():

    element = browser.find_by_xpath('//select[@id="xyz"]//option[@value="3"]').first
    element.click()