如何从下拉列表中选择“### dog”?

时间:2013-02-04 21:38:33

标签: ruby selenium-webdriver

<select name="dropdown" multiple="multiple" size="2">

  <option value="1">#Ram</option>
  <option value="2">##animals</option>
  <option value="3">###cat</option>
  <option value="4">###dog</option>
  <option value="5">#kalu</option>
  <option value="6">##animals</option>
  <option value="7">###rat</option>
  <option value="8">###dog</option>
  <option value="9">#jadu</option>
  <option value="10">##animals</option>
  <option value="11">###cat</option>

</select>

现在我想选择#{1}},它出现在#kalu-&gt; ## animals-&gt; ### dog之后 - 这是我要给的输入。但现在 要点是如何选择正确的###dog

2 个答案:

答案 0 :(得分:1)

我认为您必须获得所有选项并确定每个选项的路径(即父项)。

以下内容适用于您的html示例。希望我没有做太多的假设。

#This is the option (path) you want to select
option_to_select = '#kalu->##animals->###dog'

#Get the select list
dropdown = Selenium::WebDriver::Support::Select.new(driver.find_element(:name => 'dropdown'))

#Get the text of all options
option_text = dropdown.options.collect(&:text)

#For each option, determine its full path and value
paths = {}
option_text.each_with_index do |text, index|
    level = text[/^(#+)/].length
    segment = option_text[0..index]
    path = []
    1.upto(level) do |i|
        path << segment[segment.rindex{ |x| x =~ /^#{'#' * i}\w/ }]
    end
    paths[path.join('->')] = (index + 1).to_s
end

#Convert the desired option path to a value and select it from the dropdown
dropdown.select_by(:value, paths[option_to_select])

答案 1 :(得分:0)

Sizzle必须支持CSS选择器:

driver.find_element(:css, "select option:contains('###dog'):last")