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

4

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?

Aery answered 23/5, 2014 at 22:6 Comment(0)
J
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()
Justitia answered 23/5, 2014 at 22:16 Comment(4)
It gives me the following error: "AttributeError: 'ElementList' object has no attribute '_element'"Aery
@Aery oops, edited the answer (find_by_id() returns a list, need to get the first item from it).Justitia
@Aery ok, please check the UPD section.Justitia
@Aery I suspect this is because the select doesn't have a name.Justitia
K
1

try

browser.find_option_by_text('pick3').first.click() 
Kalin answered 20/5, 2016 at 6:34 Comment(0)
D
1

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

browser.find_by_id('xyz').select_by_text("pick3")
Difficult answered 26/9, 2017 at 4:43 Comment(0)
F
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.

Frangos answered 18/2, 2016 at 20:26 Comment(1)
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.Rutile

© 2022 - 2024 — McMap. All rights reserved.