【问题标题】:Selenium and xpath: finding a div with a class/id and verifying text insideSelenium 和 xpath:找到一个带有类/ID 的 div 并验证里面的文本
【发布时间】:2013-09-05 09:49:40
【问题描述】:

我正在尝试让 xpath 找到 div 并验证 div 内部是否有特定的 string 文本。

这是HTML

<div class="Caption">
  Model saved
</div>

<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
  Save to server successful
</div>

这是我目前正在使用的代码:

viewerHelper_.getWebDriver().findElement(By.xpath("//div[contains(@class, 'Caption' and .//text()='Model saved']"));
viewerHelper_.getWebDriver().findElement(By.xpath("//div[@id='alertLabel'] and .//text()='Save to server successful']"));

具体来说:

//div[contains(@class, 'Caption' and .//text()='Model saved']
//div[@id='alertLabel'] and .//text()='Save to server successful']

【问题讨论】:

    标签: java testing xpath selenium


    【解决方案1】:

    要验证这一点:-

    <div class="Caption">
      Model saved
    </div>
    

    写这个-

    //div[contains(@class, 'Caption') and text()='Model saved']
    

    并验证这一点:-

    <div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
      Save to server successful
    </div>
    

    写这个-

    //div[@id='alertLabel' and text()='Save to server successful']
    

    【讨论】:

    • 只是好奇,有没有办法使用findElement(By.className("") 实现与上述相同的目标?如果是这样,要验证的文本会去哪里?谢谢。
    【解决方案2】:

    要考虑前导和尾随空格,您可能需要使用normalize-space()

    //div[contains(@class, 'Caption') and normalize-space(.)='Model saved']
    

    //div[@id='alertLabel' and normalize-space(.)='Save to server successful']
    

    请注意,//div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved'] 也可以使用。

    【讨论】:

      【解决方案3】:

      对于类和文本 xpath-

      //div[contains(@class,'Caption') and (text(),'Model saved')]
      

      对于类和 id xpath-

      //div[contains(@class,'gwt-HTML') and @id="alertLabel"]
      

      【讨论】:

      • 第一个 xpath 无效(用 FirePath 检查)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      相关资源
      最近更新 更多