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
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.
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.
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));
This will help you to check whether required text is there in webpage or not.
driver.getPageSource().contains("Text which you looking for");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With