thitemple
thitemple

Reputation: 6059

Finding text on page with Selenium 2

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

Upvotes: 15

Views: 22289

Answers (4)

Thunderforge
Thunderforge

Reputation: 20595

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.

Upvotes: 0

Amith
Amith

Reputation: 7018

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);

Upvotes: 2

Grooveek
Grooveek

Reputation: 10094

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!");

Upvotes: 18

MarkHu
MarkHu

Reputation: 1869

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')]

Upvotes: 0

Related Questions