Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to have xpath find a div and verify that the div has a specific string 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']
like image 575
Chris Byatt Avatar asked Sep 02 '13 10:09

Chris Byatt


3 Answers

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']
like image 146
Arup Rakshit Avatar answered Oct 10 '22 15:10

Arup Rakshit


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.

like image 27
paul trmbrth Avatar answered Oct 10 '22 16:10

paul trmbrth


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"]
like image 4
Aashi Avatar answered Oct 10 '22 15:10

Aashi