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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18570622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:06:21  来源:igfitidea点击:

Selenium and xpath: finding a div with a class/id and verifying text inside

javatestingxpathselenium

提问by Chris Byatt

I'm trying to have xpathfind a divand verify that the divhas a specific stringof text inside.

我试图xpath找到一个div并验证里面div有特定string的文本。

Here's the HTML:

这是HTML

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

and

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

This is the code I'm using at the moment:

这是我目前使用的代码:

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']"));

Specifically:

具体来说:

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

采纳答案by Arup Rakshit

To verify this:-

要验证这一点:-

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

Write this -

写这个——

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

And to verify this:-

并验证这一点:-

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

Write this -

写这个——

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

回答by paul trmbrth

To account for leading and trailing whitespace, you probably want to use normalize-space()

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

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

and

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

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

请注意,这//div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved']也有效。

回答by Aashi

For class and text -

对于类和文本 -

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

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

and

For class and id -

对于班级和 id -

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

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