How to Verify Page Title in Selenium WebDriver

Profile picture for user arilio666

When we are working with selenium, sometimes there comes a need to verify the page title. Generally, page title verification needs to be done when we work around a web application.

We have to verify the page title, and we must do as we navigate to different pages. This may act as a checkpoint on where we currently are.

We can verify the title in selenium using the following command.

driver.getTitle();

We can also use the contain() method and verify the text.

driver.getTitle().contain(“text”);

Example:


    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://www.autopract.com");
        driver.manage().window().maximize();
        JavascriptExecutor j = driver;
        if (j.executeScript("return document.readyState").toString().equals("complete")) {
            System.out.println("Page has loaded");
        }
        driver.findElement(By.xpath("//button[@class='close']")).click();
        System.out.println(driver.getTitle());
        String expectedTitle = "Auto Pract";
        String title = driver.getTitle();
        if (title.equalsIgnoreCase(expectedTitle)) {
            System.out.println("Title Matched");
        } else {
            System.out.println("Not a match");
        }
    }
}
  • Here is a code to verify the title using the string from the getTitle method.
  • We are using the "if statement" we can verify the title using equalsIgnoreCase with the expectedTitle variable stored string.
How to Verify Page Title in Selenium WebDriver
  • We can see it has passed.

We can also assert to verify the page title.

        Assert.assertEquals(title, expectedTitle, "Matched");
  • This is done by passing the title variable, which is the actual title, with expectedTitle, our custom variable with the string.