6

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?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

4 Answers4

8

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()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

try

browser.find_option_by_text('pick3').first.click() 
Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34
Naveen
  • 485
  • 1
  • 5
  • 14
1

You can also try the following using select_by_text() method-

browser.find_by_id('xyz').select_by_text("pick3")
0

Since i'm bumping up against this right now I thought i'd chime in on this. Finding the select element and doing 'select(option_value)' does this xpath: '//select[@name="%s"]/option[@value="%s"]' to find the option. This xpath fails if you're using optgroups like in your example.

element = browser.find_by_xpath('//select[@id="xyz"]//option[@value="3"]').first element.click() as alecxe suggests should do the trick.

stewbawka
  • 21
  • 4
  • This answer seems to be an acknowledgement that another answer worked. We're glad that it did -- But instead of a new post or a comment, an upvote would be most appropriate. – Litty Feb 18 '16 at 20:54