Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Selenium2, how do I check if certain text exists on the page?

I am using the C# Selenium WebDriver and I would like to confirm that certain text exists on the page.

How do I do this? All the selectors seem to use IDs, Classes etc. I don't care where the text is on the page, I just want to make sure it exists somewhere on the page.

Any thoughts?

PS: I can do this using JQuery and Javascript, but apparently that's not supported in all browser drivers:

protected bool TextIsOnThePage(string textToFind)
{
    var javascriptExecutor = ((IJavaScriptExecutor)_driver);
    bool textFound = Convert.ToBoolean(javascriptExecutor.ExecuteScript(string.Format("return $('*:contains(\"{0}\")').length > 0", textToFind)));

    return textFound;
}
like image 647
willem Avatar asked Aug 11 '11 12:08

willem


People also ask

How can you check whether a particular text present on a webpage?

There are more than one ways to find it. We can use the getPageSource() method to fetch the full page source and then verify if the text exists there. This method returns content in the form of string. We can also check if some text exists with the help of findElements method with xpath locator.

How do you check if a text is highlighted on the page in Selenium?

Hey Karan, you can use following code snippet to check whether a text is highlighted on a page using Selenium: String color = driver. findElement(By. xpath("//a[text()='Shop']")).

What are the methods used to verify the existence of an object in a webpage?

isDisplayed() is the method used to verify a presence of a web element within the webpage.


2 Answers

Here's an updated version using Selenium WebDriver 2.48.0

IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
driver.Navigate().GoToUrl("http://stackoverflow.com/");
IWebElement body = driver.FindElement(By.TagName("body"));

Assert.IsTrue(body.Text.Contains("Top Questions"));

Note: The Assert is an Nunit assert, you can obviously use whichever assertion method you prefer. I'm also using the RemoteWebDriver and Firefox for this example.

like image 60
j3r3m7 Avatar answered Oct 18 '22 23:10

j3r3m7


WebElement bodyTag = driver.findElement(By.tagName("body")); 
if (bodyTag.getText().contains("Text I am looking for") { 
  // do something 
} 

or find a speific div

or you can use the Selenium class WebDriverBasedSelenium and do something like

var selenium=new WebDriverBasedSelenium(driver,url);

selenium.IsTextPresent("text")
like image 29
Baz1nga Avatar answered Oct 18 '22 23:10

Baz1nga