使用Selenium2,如何检查页面上是否存在某些文本?

wil*_*lem 10 c# selenium selenium-webdriver

我正在使用C#Selenium WebDriver,我想确认页面上存在某些文本.

我该怎么做呢?所有选择器似乎都使用ID,类等.我不关心文本在页面上的位置,我只是想确保它存在于页面的某个位置.

有什么想法吗?

PS:我可以使用JQuery和Javascript来做到这一点,但显然所有浏览器驱动程序都不支持:

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;
}
Run Code Online (Sandbox Code Playgroud)

Baz*_*nga 13

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

或找到一个特殊的div

或者您可以使用Selenium类WebDriverBasedSelenium并执行类似的操作

var selenium=new WebDriverBasedSelenium(driver,url);

selenium.IsTextPresent("text")
Run Code Online (Sandbox Code Playgroud)


j3r*_*3m7 5

这是使用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"));
Run Code Online (Sandbox Code Playgroud)

注意:Assert是一个Nunit断言,显然你可以使用你喜欢的任何断言方法.我也在使用RemoteWebDriver和Firefox这个例子.