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 aStringof the page title. - Python: Use
driver.titleproperty which returns the title as astr.
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 ofdriver.titlewill 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
| Language | Method to Get Page Title |
|---|---|
| Java | driver.getTitle() |
| Python | driver.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.