Selenium和xpath:找到一个带有类/ id的div并验证里面的文本

时间:2013-09-02 10:09:18

标签: java testing xpath selenium

我尝试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']

3 个答案:

答案 0 :(得分:36)

验证这一点: -

<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']

答案 1 :(得分:6)

要考虑前导空格和尾随空格,您可能希望使用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']也有效。

答案 2 :(得分:2)

课程和文字 -

// div [contains(@class,&#39; Caption&#39;)和(text(),&#39; Model saved&#39;)]

对于class和id -

// div [contains(@class,&#39; gwt-HTML&#39;)和@id =&#34; alertLabel&#34;]