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

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

This question is related to validation selenium webdriver assert

The answer is


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

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)

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.


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


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

driver.getPageSource().contains("Text which you looking for");

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

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

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

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.


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

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


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

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to webdriver

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? ImportError: No module named 'selenium' how to use List<WebElement> webdriver How to get attribute of element from Selenium? Selenium Finding elements by class name in python Open web in new tab Selenium + Python When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly How can I start InternetExplorerDriver using Selenium WebDriver

Examples related to assert

What is “assert” in JavaScript? How to handle AssertionError in Python and find out which line or statement it occurred on? How can I check if some text exist or not in the page using Selenium? PHPUnit assert that an exception was thrown? What is the use of "assert"? How do I check (at runtime) if one class is a subclass of another? Java/ JUnit - AssertTrue vs AssertFalse What does the "assert" keyword do? Proper way to assert type of variable in Python How to check if an object is a list or tuple (but not string)?