55

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

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
khris
  • 4,809
  • 21
  • 64
  • 94
  • In case anyone looking for same in Robot Framework - this may help -https://stackoverflow.com/questions/54242291/robotframework-how-to-check-text-on-page – Dev May 19 '19 at 19:21

12 Answers12

52

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));
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • I get notification - WebElement cannot be resolved to a type, Assert cannot be resolved to a type, List cannot be resolved to a type - I need add something ti import to resolve this? – khris Jul 13 '12 at 09:39
  • 2
    Do you remember the shortcuts I told you yesterday? They help ;-). If you're working with Java, you should know where the [`List`](http://docs.oracle.com/javase/7/docs/api/java/util/List.html) lies. If you're working with the Selenium library, you should know where the [`WebElement`](http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html) lies. And if you added `assert` tag to your question and use Java, you should know where [`Assert`](http://junit.sourceforge.net/javadoc/org/junit/Assert.html) lies (needs JUnit)... – Petr Janeček Jul 13 '12 at 09:43
  • 1
    sorry for such question, I'm new to selenium and java) – khris Jul 13 '12 at 10:32
  • Getting the body text is not the right way to search for text on a page. Getting the body text will test if the string exists in the source code, but it doesn't really test that the string exists on a page. For example, there may be broken PHP script where a closing ?> is missing, meaning the test will pass, but the page will not be rendering correctly. – Vanessa Deagan Mar 21 '18 at 15:20
  • .size() not working for me in NodeJS. I ended up going with the .getPageSource() solution below. – RedDragonWebDesign Jan 25 '23 at 05:10
24

This will help you to check whether required text is there in webpage or not.

driver.getPageSource().contains("Text which you looking for");
Rohit Ware
  • 1,982
  • 1
  • 13
  • 29
  • 11
    `AttributeError: 'WebDriver' object has no attribute 'getPageSource'` – Cerin Jul 07 '17 at 00:19
  • 1
    @Cerin It looks like you're in Python? This post is likely in Java, so you might want to adapt it to `get_page_source`. (I haven't checked this one specifically, but mostly camelCase becomes snake_case.) – Nuclear03020704 Feb 12 '22 at 17:24
14

You could retrieve the body text of the whole page like this:

bodyText = self.driver.find_element_by_tag_name('body').text

then use an assert to check it like this:

self.assertTrue("the text you want to check for" in bodyText)

Of course, you can be specific and retrieve a specific DOM element's text and then check that instead of retrieving the whole page.

kenorb
  • 155,785
  • 88
  • 678
  • 743
JCarter
  • 407
  • 3
  • 11
  • 1
    If you're going to assert and check if an element is in something, I'd recommend `self.assertIn("the text you want to check for", bodyText)` – Kevin London Sep 18 '14 at 01:14
7

There is no verifyTextPresent in Selenium 2 webdriver, so you've to check for the text within the page source. See some practical examples below.

Python

In Python driver you can write the following function:

def is_text_present(self, text):
    return str(text) in self.driver.page_source

then use it as:

try: self.is_text_present("Some text.")
except AssertionError as e: self.verificationErrors.append(str(e))

To use regular expression, try:

def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
    self.assertRegex(self.driver.page_source, text)
    return True

See: FooTest.py file for full example.

Or check below few other alternatives:

self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text

Source: Another way to check (assert) if text exists using Selenium Python

Java

In Java the following function:

public void verifyTextPresent(String value)
{
  driver.PageSource.Contains(value);
}

and the usage would be:

try
{
  Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
  Console.WriteLine("Selenium Wiki test is present on the home page");
}
catch (Exception)
{
  Console.WriteLine("Selenium Wiki test is not present on the home page");
}

Source: Using verifyTextPresent in Selenium 2 Webdriver


Behat

For Behat, you can use Mink extension. It has the following methods defined in MinkContext.php:

/**
 * Checks, that page doesn't contain text matching specified pattern
 * Example: Then I should see text matching "Bruce Wayne, the vigilante"
 * Example: And I should not see "Bruce Wayne, the vigilante"
 *
 * @Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
 */
public function assertPageNotMatchesText($pattern)
{
    $this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
}

/**
 * Checks, that HTML response contains specified string
 * Example: Then the response should contain "Batman is the hero Gotham deserves."
 * Example: And the response should contain "Batman is the hero Gotham deserves."
 *
 * @Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
 */
public function assertResponseContains($text)
{
    $this->assertSession()->responseContains($this->fixStepArgument($text));
}
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
kenorb
  • 155,785
  • 88
  • 678
  • 743
3

In c# this code will help you to check whether required text is there in webpage or not.

Assert.IsTrue(driver.PageSource.Contains("Type your text here"));
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
mpaul
  • 27
  • 5
2

You can check for text in your page source as follow:

Assert.IsTrue(driver.PageSource.Contains("Your Text Here"))
2

In python, you can simply check as follow:

# on your `setUp` definition.
from selenium import webdriver
self.selenium = webdriver.Firefox()

self.assertTrue('your text' in self.selenium.page_source)
Adiyat Mubarak
  • 10,279
  • 4
  • 34
  • 50
2

Python:

driver.get(url)
content=driver.page_source
if content.find("text_to_search"): 
    print("text is present in the webpage")

Download the html page and use find()

Dipankar Nalui
  • 1,121
  • 5
  • 18
  • 33
0
  boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
    if (Error == true)
    {
     System.out.print("Login unsuccessful");
    }
    else
    {
     System.out.print("Login successful");
    }
fart
  • 1
0

JUnit+Webdriver

assertEquals(driver.findElement(By.xpath("//this/is/the/xpath/location/where/the/text/sits".getText(),"insert the text you're expecting to see here");

If in the event your expected text doesn't match the xpath text, webdriver will tell you what the actual text was vs what you were expecting.

Dan
  • 1
  • 1
0

string_website.py

search string in webpage

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    browser = webdriver.Firefox()
    browser.get("https://www.python.org/")
    content=browser.page_source

    result = content.find('integrate systems')
    print ("Substring found at index:", result ) 

    if (result != -1): 
    print("Webpage OK")
    else: print("Webpage NOT OK")
    #print(content)
    browser.close()

run

python test_website.py
Substring found at index: 26722
Webpage OK


d:\tools>python test_website.py
Substring found at index: -1 ; -1 means nothing found
Webpage NOT OK

Tek Nath Acharya
  • 1,676
  • 2
  • 20
  • 35
tng
  • 1
0

You can check a source code if the text exists:

   source_code = driver.page_source
   if "Im not a Robot" not in source_code:
warfish
  • 613
  • 5
  • 20