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;
import org.openqa.selenium.chrome.ChromeDriver;

public class RetrievingPageTitleWithoutGetTitle {

	public static void main(String[] args) throws InterruptedException {
		
		System.setProperty("webdriver.chrome.driver","./exefiles/chromedriver.exe");
		WebDriver driver= new ChromeDriver();
		
		driver.manage().window().maximize();
		
		driver.get("https://www.google.com/");
		
		// 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
		driver.quit();
	}
}

Output:

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 *