开发者

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 JQ开发者_开发知识库uery 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;
}


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


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.


You should be able to achieve this by checking the inner text of <body />.


In java you do it like so:

boolean whatever = driver.getPageSource().contains("Whatever your trying to find");


Easiest thing I found was to search for a class

IWebElement thing = driver.FindElement(By.ClassName("thingClass"));

Assert.IsTrue(thing.Text.Contains("YourText"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜