HTML代码:
<div id="empid" title="Please first select a list to filter!"><input value="5418630" name="candidateprsonIds" type="checkbox">foo <input value="6360899" name="candidateprsonIds" type="checkbox"> bar gui<input value="9556609" name="candidateprsonIds" type="checkbox"> bab </div>
现在我想使用selenium-webdriver作为
来获得以下内容[[5418630,foo],[6360899,bar gui],[9556609,bab]]
可以吗?
我尝试了以下代码:
driver.find_elements(:id,"filtersetedit_fieldNames").each do |x|
puts x.text
end
但它在我的控制台上以字符串"foo bar gui bab"
提供数据。因此无法弄清楚 - 如何创建如此高于预期的Hash
。
有关这方面的任何帮助吗?
答案 0 :(得分:1)
我知道获取类似文本节点的唯一方法是使用execute_script
方法。
以下脚本将为您提供选项值及其后续文本的哈希值。
#The div containing the checkboxes
checkbox_div = driver.find_element(:id => 'empid')
#Get all of the option values
option_values = checkbox_div.find_elements(:css => 'input').collect{ |x| x['value'] }
p option_values
#=> ["5418630", "6360899", "9556609"]
#Get all of the text nodes (by using javascript)
script = <<-SCRIPT
text_nodes = [];
for(var i = 0; i < arguments[0].childNodes.length; i++) {
child = arguments[0].childNodes[i];
if(child.nodeType == 3) {
text_nodes.push(child.nodeValue);
}
}
return text_nodes
SCRIPT
option_text = driver.execute_script(script, checkbox_div)
#Tidy up the text nodes to get rid of blanks and extra white space
option_text.collect!(&:strip).delete_if(&:empty?)
p option_text
#=> ["foo", "bar gui", "bab"]
#Combine the two arrays to create a hash (with key being the option value)
option_hash = Hash[*option_values.zip(option_text).flatten]
p option_hash
#=> {"5418630"=>"foo", "6360899"=>"bar gui", "9556609"=>"bab"}