15

How can I check whether a given text string is present on the current page using Selenium?

4 Answers 4

18

The code is this:

def elem = driver.findElement(By.xpath("//*[contains(.,'search_text')]")); if (elem == null) println("The text is not found on the page!"); 
Sign up to request clarification or add additional context in comments.

2 Comments

The above is not technically true for selenium in .Net. If the element is not found it will throw a NoSuchElementException. Also note that the xpath contains is case sensitive
Selenium 2 with WebForms gets a little tedious. I created some wrapper methods that make it a little easier. foliotek.com/devblog/…
2

If your searching the whole page for some text , then providing an xpath or selector to find an element is not necessary. The following code might help..

Assert.assertEquals(driver.getPageSource().contains("text_to_search"), true); 

1 Comment

This will find text that exists in the source, but is not visible to the user. For instance, if you are searching for the word "body", then this will always return true. This solution also does not use XPaths, but only finds visible text. Also, that solution includes the text that does in the assertion error to assist in debugging.
0

For some reason, certain elements don't seem to respond to the "generic" search listed in the other answer. At least not in Selenium2library under Robot Framework which is where I needed this incantation to find the particular element:

xpath=//script[contains(@src, 'super-sekret-url.example.com')] 

Comments

0

A simpler (but probably less efficient) alternative to XPaths is to just get all the visible text in the page body like so:

def pageText = browser.findElement(By.tagName("body")).getText(); 

Then if you're using JUnit or something, you can use an assertion to check that the string you are searching for is contained in it.

assertThat("Text not found on page", pageText, containsString(searchText)); 

Using an XPath is perhaps more efficient, but this way is simpler to understand for those unfamiliar with it. Also, an AssertionError generated by assertThat will include the text that does exist on the page, which may be desirable for debugging as anybody looking at the logs can clearly see what text is on the page if what we are looking for isn't.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.