Selecting element from dropdown without id Capybara

廉价感情. 提交于 2020-01-06 12:50:50

问题


I am trying to use capybara (ruby bindings) to select an item from a dropdown that does not have an id or unique class, but I seem to be unable to do so.

The select box in question looks like this:

<select data-bind="options: environments, optionsText: 'name', value: selectedEnvironment,   optionsCaption: 'Choose...'" class="form-control">

Trying to do a:

select("option",:from "#panel > div.panel-body > form > div:nth-child(1) > select")

does not work, but I am able to find the select field using a

page.find("#panel > div.panel-body > form > div:nth-child(1) > select")

The documentation says that the select method expects an id, name or label of the select box, but surely there must be a way of selecting something from a dropdown that is more specific than this. Is there another method I can use other than select() or do I have to go back to using pure selenium?


回答1:


If you want more control over which option you select, you will need to:

  1. Find the option element (using find, all, etc)
  2. Use the select_option method

For example, if you wanted to just select the first option:

option = page.first("#panel > div.panel-body > form > div:nth-child(1) > select option")
option.select_option

Or if you wanted to select the last:

options = page.all("#panel > div.panel-body > form > div:nth-child(1) > select option")
options[-1].select_option


来源:https://stackoverflow.com/questions/23360046/selecting-element-from-dropdown-without-id-capybara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!