Selenium and xpath: finding a div with a class/id and verifying text inside
151,578
Solution 1
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']
Solution 2
To account for leading and trailing whitespace, you probably want to use 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.
Solution 3
For class and text xpath-
//div[contains(@class,'Caption') and (text(),'Model saved')]
and
For class and id xpath-
//div[contains(@class,'gwt-HTML') and @id="alertLabel"]
Related videos on Youtube
Author by
Chris Byatt
Updated on January 26, 2021Comments
-
Chris Byatt over 3 years
I'm trying to have
xpath
find adiv
and verify that thediv
has a specificstring
of text inside.Here's the
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']
-
Siva almost 10 yearsJust curious, is there a way to achieve the same objective as above using
findElement(By.className("")
? If so, where would the text to be verfified go? Thanks. -
Andrejs about 7 yearsFirst xpath is invalid (checked with FirePath)