How can I check if some text exist or not in the page using Selenium?

khris picture khris · Jul 12, 2012 · Viewed 258.3k times · Source

I'm using Selenium WebDriver, how can I check if some text exist or not in the page? Maybe someone recommend me useful resources where I can read about it. Thanks

Answer

Petr Janeček picture Petr Janeček · Jul 12, 2012

With XPath, it's not that hard. Simply search for all elements containing the given text:

List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertTrue("Text not found!", list.size() > 0);

The official documentation is not very supportive with tasks like this, but it is the basic tool nonetheless.

The JavaDocs are greater, but it takes some time to get through everything useful and unuseful.

To learn XPath, just follow the internet. The spec is also a surprisingly good read.


EDIT:

Or, if you don't want your Implicit Wait to make the above code wait for the text to appear, you can do something in the way of this:

String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains(text));