使用Java获取Selenium WebDriver的页面标题

时间:2011-12-14 14:52:53

标签: java selenium selenium-webdriver

如何使用Selenium WebDriver和java验证标题标签中的某些文本?

5 个答案:

答案 0 :(得分:16)

您可以使用JUnit或TestNG框架轻松完成。做断言如下:

String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);

OR,

assertTrue(driver.getTitle().contains("Title of Page"));

答案 1 :(得分:3)

如果你正在使用Selenium 2.0 / Webdriver,你可以打电话 如果您想搜索实际的网页来源,请driver.getTitle()driver.getPageSource()

答案 2 :(得分:3)

在java中你可以做一些事情:

if(driver.getTitle().contains("some expected text"))
    //Pass
    System.out.println("Page title contains \"some expected text\" ");
else
    //Fail
    System.out.println("Page title doesn't contains \"some expected text\" ");

答案 3 :(得分:2)

可以通过Selenium获取页面标题并使用TestNG进行断言来完成。

  1. 导入部分中的导入Assert类:

    `import org.testng.Assert;`
    
  2. 创建WebDriver对象:

    WebDriver driver=new FirefoxDriver();

  3. 应用此方法断言页面标题:

    Assert.assertEquals("Expected page title", driver.getTitle());

答案 4 :(得分:0)

您可以使用Selenium Testng框架通过断言轻松地做到这一点。

步骤:

1。创建Firefox浏览器会话

2。初始化期望的标题名称。

3。导航到“ www.google.com” [根据您的要求,您可以更改],然后等待一段时间(15秒)以完全加载页面。

4。使用“ driver.getTitle()”获取实际的标题名称,并将其存储在String变量中。

5。应用如下的断言, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle),“页面标题名称不匹配或加载网格时出现问题”);

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;

public class PageTitleVerification
{   
private static WebDriver driver = new FirefoxDriver();

@Test
public void test01_GooglePageTitleVerify()
{               
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";      
Utility.waitForElementInDOM(driver, "Google Search", 15);   
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);   
//Verify expected page title and actual page title is same  
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle 
),"Page title not matched or Problem in loading url page");     
}
}

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utility {

/*Wait for an element to be present in DOM before specified time (in seconds ) has 
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier, 
long timeOutInSeconds) 
{       
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds        
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier))); 
}
catch(NoSuchElementException e)
{           
e.printStackTrace();
}           
}
}