0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

How to Get Page Title in Selenium: Simple Guide

To get the page title in Selenium, use the driver.getTitle() method in Java or driver.title in Python. This returns the current page's title as a string, which you can use for verification in your tests.
๐Ÿ“

Syntax

The method to get the page title depends on the language binding you use with Selenium.

  • Java: Use driver.getTitle() which returns a String of the page title.
  • Python: Use driver.title property which returns the title as a str.

Here, driver is your WebDriver instance controlling the browser.

java
String title = driver.getTitle();

// or in Python

title = driver.title
๐Ÿ’ป

Example

This example shows how to open a webpage and print its title using Selenium WebDriver in Java.

java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class GetTitleExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.example.com");
        String title = driver.getTitle();
        System.out.println("Page title is: " + title);
        driver.quit();
    }
}
Output
Page title is: Example Domain
โš ๏ธ

Common Pitfalls

  • Trying to get the title before the page fully loads can return an empty or old title.
  • Using incorrect WebDriver instance or forgetting to initialize it causes errors.
  • In Python, calling driver.getTitle() (Java method) instead of driver.title will fail.

Always ensure the page is loaded before getting the title.

java
/* Wrong in Java: */
// String title = driver.title; // This will not compile

/* Correct in Java: */
String title = driver.getTitle();

# Wrong in Python:
# title = driver.getTitle()  # AttributeError

# Correct in Python:
title = driver.title
๐Ÿ“Š

Quick Reference

LanguageMethod to Get Page Title
Javadriver.getTitle()
Pythondriver.title
C#driver.Title
JavaScript (WebDriverJS)driver.getTitle()
โœ…

Key Takeaways

Use driver.getTitle() in Java and driver.title in Python to get the page title.
Ensure the page is fully loaded before retrieving the title to get accurate results.
Avoid mixing language-specific methods; use the correct syntax for your language binding.
Always initialize your WebDriver instance before calling methods on it.