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
Selenium and xpath: finding a div with a class/id and verifying text inside
提问by Chris Byatt
I'm trying to have xpath
find a div
and verify that the div
has a specific string
of 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"]