Selenium 和 xpath:查找具有 class/id 的 div 并验证其中的文本

2022-09-01 15:15:19

我正在尝试找到一个并验证里面有特定的文本。xpathdivdivstring

这是: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']

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

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