【问题标题】:Finding an Image Icon Next to a Text Item in Watir-WebDriver在 Watir-WebDriver 中查找文本项旁边的图像图标
【发布时间】:2014-03-14 17:07:48
【问题描述】:

上下文是我正在使用 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 项目。 (上面的省略号只是表示我可以有很多列表项。)

我希望我们的自动化做的是找出文章是否已适当地被赋予图像 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 区域中的任何链接 (a) 标记。检查链接是否有文本,然后“备份”一级以查看是否存在图像。

我什至没有检查确切的图像,我可能应该检查。我只是在检查是否有图像。

所以我想我的问题是:

  • 我的 XPath 有什么问题?
  • 这甚至是解决此问题的最佳方法吗?

【问题讨论】:

    标签: ruby xpath watir-webdriver


    【解决方案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 中阅读有关这些方法和其他选项的更多信息。

    【讨论】:

    • 这非常有用。我对您的回复表示最深切的感谢。我也在调查你提到的 Watirways 参考资料。感谢您的帮助。
    猜你喜欢
    • 2021-05-06
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2015-06-15
    相关资源
    最近更新 更多