上下文是我正在使用watir-webdriver,我需要找到一个图像是否出现在列表中的特定项目之前。
更具体地说,该网站的一部分上传了文章。这些文章出现在一个列表中。结构如下所示:
<div id="article-resources"
<ul class="components">
...
<li>
<div class="component">
<img src="some/path/article.png">
<div class="replies">
<label>Replies</label>
</div>
<div class="subject">
<a href="/article">Saving the Day</a>
</div>
</div>
</li>
...
</ul>
</div>
每篇文章都显示为单独的li项目。 (上面的省略号只是表示我可以拥有大量的侦听项目。)
我希望我们的自动化功能是找出文章是否适当地给了image article.png。诀窍是我需要确保实际的文章 - 在上面的例子中,“拯救一天” - 旁边有图像。我不能只检查图像,因为会有倍数。
所以我想我必须使用xpath来解决这个问题。使用Firefox帮助查看xpath给了我:
id("article-resources")/x:ul/x:li[2]/x:div/x:img
这对我没有好处,因为关键鉴别器似乎是li [2],但我不能指望这篇文章总是列表中的第二位。
所以我尝试了这个:
article_image = '//div[@class="component"]/a[contains(.,"Saving the Day")]/../img'
@browser.image(:xpath => article_image).exist?.should be_true
我得到的输出是:
expected: true value
got: false (RSpec::Expectations::ExpectationNotMetError)
因此我没有找到可能意味着我做错事的图像,因为我确定测试是在正确的页面上。
我的想法是我可以使用上面的内容来获取div区域中引用为类“component”的任何链接(a)标记。检查链接是否包含文本,然后“备份”一个级别以查看是否有图像。
我甚至没有检查确切的图像,我可能应该这样做。我只是在检查是否有图像。
所以我想我的问题是:
答案 0 :(得分:1)
使用Watir
有几种可能的方法。
一种方法是找到链接,转到组件div,然后检查图像:
browser.link(:text => 'Saving the Day').parent.parent.image.present?
或
browser.div(:class => 'subject', :text => 'Saving the Day').parent.image.present?
另一种对变化更加健壮的方法是找到包含链接的组件div:
browser.divs(:class => 'component').find { |component|
component.div(:class => 'subject', :text => 'Saving the Day').exists?
}.image.present?
使用XPath
上述当然也可以通过xpath完成。
以下是您更正的xpath:
article_image = '//div[@class="component"]//a[contains(.,"Saving the Day")]/../../img'
puts browser.image(:xpath => article_image).present?
或者:
article_image = '//a[contains(.,"Saving the Day")]/../../img'
browser.image(:xpath => article_image).present?
同样,还有自上而下的方法:
article_image = '//div[@class="component"][//a[contains(.,"Saving the Day")]]/img'
browser.image(:xpath => article_image).present?
您可以在书籍Watirways中了解有关这些方法和其他选项的更多信息。