在Watir中,您可以通过直接访问win32ole对象来访问元素字体权重。例如:
ie.div(:index, 1).document.currentStyle.fontWeight
这在http://www.w3schools.com/cssref/pr_font_weight.asp
描述我现在想什么,你需要做的是通过检查其fontWeight设置是什么网页上的所有元素循环会给你代表重量的号码,元素中有多少文字。你这样做的方式将取决于你正在测试的页面。
解决方案1 - 如果所有的文本是div的是叶子节点:
如果你的所有文字是这样的叶子节点:
<body>
<div style='font-weight:bold'>Bold</div>
<div>Plain</div>
</body>
你可以很容易做到:
bold_text = 0
plain_text = 0
ie.divs.each{ |x|
if x.document.currentStyle.fontWeight >= 700
bold_text += x.text.length
else
plain_text += x.text.length
end
}
解决方案2 - 如果样式相互作用或使用多个元素:
如果不是所有文本都在叶节点中,或者您使用其他标签(如<b>
)(请参阅下面的示例HTML),则需要更复杂的检查。这是由于.text返回元素中的所有文本,包括其子元素。
<body>
<div style='font-weight:normal'>
Start
<div style='font-weight:bold'>Bold1</div>
<div style='font-weight:bold'>Bold2</div>
End
</div>
<b>Bold Text</b>
</body>
在这种情况下,我相信下面的作品大多数情况下(但可能需要细化):
#Counting letters, but you could easily change to words
bold_count = 0
plain_count = 0
#Check all elements, though you can change this to restrict to a particular containing element if desired.
node_list = ie.document.getElementsByTagName("*")
0.upto(node_list.length-1) do |i|
#Name the node so it is easier to work with.
node = node_list["#{i}"]
#Determine if the text for the current node is bold or not.
#Note that this works in IE. You might need to modify for other browsers.
if node.currentStyle.fontWeight >= 700
bold = true
else
bold = false
end
#Go through the childNodes. If the node is text, count it. Otherwise ignore.
node.childNodes.each do |child|
unless child.nodeValue.nil?
if bold
bold_count += child.nodeValue.length
else
plain_count += child.nodeValue.length
end
end
end
end
#Determine number of characters that are bold and not. These can be used to determine your percentage.
puts bold_count
puts plain_count
这是不是一个非常的Watir样的解决方案,但希望解决您的问题。
按地区“百分比”?通过字数? – 2012-03-01 21:09:05
Word可能会工作。 – 2012-03-01 21:11:55