Reputation: 31
I try to select "Local Host" from the dropdown list which has the following html code:
<select id="server_select">
<option></option>
<option>
Local Host
</option>
<option>
ah005
</option>
</select>
Here is my python code to use splinter module to select "Local Host" from dropdown list but failed.
server_list = browser.find_by_xpath('//select[@id="server_select"]//option[@selected="Local Host"]').first
server_list.click()
and I got the error:
Traceback (most recent call last):
File "splinter_test.py", line 22, in <module>
server_list = browser.find_by_xpath('//select[@id="server_select"]//option[@selected="Local Host"]').first
File "/Users/Bibo_MBPR/anaconda/lib/python2.7/site-packages/splinter/element_list.py", line 53, in first
return self[0]
File "/Users/Bibo_MBPR/anaconda/lib/python2.7/site-packages/splinter/element_list.py", line 44, in __getitem__
self.find_by, self.query))
splinter.exceptions.ElementDoesNotExist: no elements could be found with xpath "//select[@id="server_select"]//option[@selected="Local Host"]"
Could someone please give me some advice? Thanks
Upvotes: 3
Views: 2146
Reputation: 315
You can use find_by_id
to get the browser element for drop down as it has the id="server_select"
option. Then you can select your option from them by text. Try the following-
server_list = browser.find_by_id('server_select')
server_list.select_by_text("Local Host")
Or,
browser.find_option_by_text("Local Host").first.click()
Upvotes: 4
Reputation: 12409
Named options are usually very helpful. But when they don't exist you have to iterate over the options to find the right one.
dropdown = browser.find_by_xpath("//select[@id='server_select']")
for option in dropdown.find_by_tag('option'):
if option.text == "Local Host":
option.click()
break
You may need to call strip()
on option.text
before comparing in case it contains extra whitespaces.
And in case that empty option at the top is causing you problems then I would change the if
case to option.text is not None and option.text == "Local Host"
.
Upvotes: 0