Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 513
khris Avatar asked Jul 12 '12 15:07

khris


People also ask

How do you validate partial text in Selenium?

text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value. contains(): Similar to the text() method, contains() is another built-in method used to locate an element based on partial text match.

How do you check if an element is present in a page in Selenium?

We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list.


2 Answers

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)); 
like image 85
Petr Janeček Avatar answered Sep 22 '22 17:09

Petr Janeček


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

driver.getPageSource().contains("Text which you looking for"); 
like image 29
Rohit Ware Avatar answered Sep 22 '22 17:09

Rohit Ware