使用Watir Webdriver选择和“ol”html标记

时间:2016-05-20 10:17:34

标签: selenium watir

我想创建一个for循环来从几个lis获取带有watir的文本。

这是我试图抓取的HTML

<ol class="shared-connections">
 <li class="small-result">
  <a class="img-link" href="http://www.google.com"></a>    
 </li>
 <li class="small-result">
  <a class="img-link" href="http://www.google.com"></a>    
 </li>
</ol>

我想通过循环获取链接中的href值,但我无法使用此代码启动循环:

@browser.ol(class: "shared-connections").lis(class: "small-result").each do |connection|
p "is this working?"
end

“ol”标签阻止循环工作并给我这个错误:

/Library/Ruby/Gems/2.0.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/elements/element.rb:536:in `assert_element_found': unable to locate element, using {:class=>"shared-connections", :tag_name=>"ol"} (Watir::Exception::UnknownObjectException)

知道如何让“ol”与Watir合作吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您似乎没有通过代码打开正确的页面。

代码运作良好。我使用您提供的代码创建了文件

in irb:

pp File.readlines('a.html')

["<ol class=\"shared-connections\">",    
 " <li class=\"small-result\">,    
 "  <a class=\"img-link\" href=\"http://www.google.com\"></a>,    
 " </li>",    
 " <li class=\"small-result\">,    
 "  <a class=\"img-link\" href=\"http://www.google.com\"></a>",        
 " </li>",    
 "</ol>"]

然后

b = Watir::Browser.new :chrome
b.goto 'file://' + Dir.pwd + '/a.html'

b.ol(class: "shared-connections").lis(class: "small-result").each do |connection|
  p "is this working?"
end
"is this working?"
"is this working?"
=> [#<Watir::LI:0x604055b6f2097db6 located=false selector={element: (webdriver element)}>, #<Watir::LI:0x..f5826cdc74313e1a located=false selector={element: (webdriver element)}>]

您可以使用@browser.html

确保这一点