0
0
Selenium Javatesting~5 mins

Page title and URL retrieval in Selenium Java

Choose your learning style9 modes available
Introduction

We get the page title and URL to check if we are on the right webpage during testing.

To confirm the browser opened the correct webpage after clicking a link.
To verify the page title matches expected content in a test case.
To log the current URL for debugging test failures.
To ensure navigation happened correctly after form submission.
To check if redirects lead to the expected page.
Syntax
Selenium Java
WebDriver driver = new ChromeDriver();

// Open a webpage
driver.get("https://example.com");

// Get page title
String pageTitle = driver.getTitle();

// Get current URL
String currentUrl = driver.getCurrentUrl();

Use getTitle() to get the page title as a String.

Use getCurrentUrl() to get the current page URL as a String.

Examples
Prints the page title to the console.
Selenium Java
String title = driver.getTitle();
System.out.println("Title: " + title);
Prints the current URL to the console.
Selenium Java
String url = driver.getCurrentUrl();
System.out.println("URL: " + url);
Opens Google, then prints its title and URL.
Selenium Java
driver.get("https://www.google.com");
String title = driver.getTitle();
String url = driver.getCurrentUrl();
System.out.println("Title: " + title);
System.out.println("URL: " + url);
Sample Program

This program opens the browser, navigates to example.com, prints the page title and URL, then closes the browser.

Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class PageInfoTest {
    public static void main(String[] args) {
        // Set path to chromedriver executable if needed
        // System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        WebDriver driver = new ChromeDriver();

        // Open example.com
        driver.get("https://example.com");

        // Get and print page title
        String pageTitle = driver.getTitle();
        System.out.println("Page Title: " + pageTitle);

        // Get and print current URL
        String currentUrl = driver.getCurrentUrl();
        System.out.println("Current URL: " + currentUrl);

        // Close the browser
        driver.quit();
    }
}
OutputSuccess
Important Notes

Getting the title and URL is fast and uses little memory (O(1) time and space).

Common mistake: calling these methods before the page fully loads can give wrong results.

Use these methods to verify navigation success instead of relying only on page content.

Summary

Use getTitle() to get the page title as a string.

Use getCurrentUrl() to get the current page URL as a string.

Check these values to confirm you are on the expected webpage during tests.