Selenium Interview Question 5 – How To Retrieve Title of a Webpage Without Using getTitle() Method

Verifying page title is basic step before proceeding for further validation. Generally we use getTitle() method which gives title of currently loaded page in browser. 

There is also an another way of retrieving title of a web page. Title of webpage is stored in “title” tag under “head” tag. We can locate “title” web element and use getAttribute(“textContent”) on it. It will give the same result. 

We can not use getText() method on title web element as it is not rendered on web page i.e. browser visible area. ‘getText()’ works well on web element defined under body tag. If you use getText() at title here, you will get empty string.

We can retrieve title using JavascriptExecutor as well. 

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class RetrievingPageTitleWithoutGetTitle {

	public static void main(String[] args) throws InterruptedException {
		WebDriver driver= new ChromeDriver();
		// Using getTitle() method
		System.out.println("Title of webpage by getTitle() method: "+driver.getTitle());
		// Using getAtttribute() method at title web element
		WebElement titleEle= driver.findElement(By.tagName("title"));
		System.out.println("Title of webpage by webelement title :"+titleEle.getAttribute("textContent"));
		// Using Javascript
		JavascriptExecutor jse = (JavascriptExecutor)driver;
		String titlebyJavascript= (String) jse.executeScript("return document.title");
		System.out.println("Title of webpage by Javascript :"+titlebyJavascript);
		// to close all window opened by driver


Title of webpage by getTitle() method: Google
Title of webpage by webelement title :Google
Title of webpage by Javascript :Google

Like, comment and share it to reach maximum. Thanks. 

Leave a Reply

Your email address will not be published. Required fields are marked *