Skip to main content
 首页 » 编程设计

c#之HTML> head> <title> selenium Firefox webdriver 为空的文本

2024年02月01日24开发

我在 Windows 7 上使用 Firefox 21 和 C# WebDriver 2.33。我对以下测试失败的原因感到困惑(我只是为了检查我的配置是否设置正确)。这在其他浏览器中通过。

[Test] 
public void FirefoxDriverWorks() 
{ 
    var firefoxDriver = new FirefoxDriver(); 
    TestGoogleStillExists(firefoxDriver); 
    firefoxDriver.Quit(); 
} 
 
public void TestGoogleStillExists(IWebDriver webDriver) 
{ 
    webDriver.Navigate().GoToUrl("http://www.google.com"); 
    var title = webDriver.FindElement(By.CssSelector("head title")); 
    Assert.That(title.Text, Is.EqualTo("Google")); 
} 

请您参考如下方法:

Selenium WebDriver 的text 函数将只返回用户在页面上可见的文本。标题文本在页面上在技术上不可见(它显示在浏览器中 chrome 的标题部分)。

相反,Selenium WebDriver 有一个方法将 return the title of a page你可以使用:

driver.Title; 

所以你的代码变成:

public void TestGoogleStillExists(IWebDriver webDriver) 
{ 
    webDriver.Navigate().GoToUrl("http://www.google.com"); 
    var title = webDriver.Title; 
    Assert.That(title, Is.EqualTo("Google")); 
}