How to use getTitle() method in selenium WebDriver

We are using getTitle() method very frequently in out selenium webdriver tests. It is one of the basic and most commonly used method. getTitle() method is used to get the title of currently loaded web page. Also it will strip leading and trailing white space from title if available. Also it can return null if title of the page is not present.

How getTitle() Works?

Let us look at the Example how getTitle() method works
package TestPack;

import org.openqa.selenium.WebDriver;

public class getPageTitle {

 public static void main(String[] args) {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("", exePath);
  WebDriver driver = new ChromeDriver();
  //Get current page title and store it in s
  String s = driver.getTitle();
  //Get result of s in console
  System.out.println("Page Title is : "+ s);

OutPut : Page Title is : Only Testing

In above example, You can see that driver.getTitle() method has retrieved title of current page and then print it in console.

When you need getTitle()?
In selenium Webdriver test, Sometimes you need to verify title of the page to make sure that targeted page is loaded or not. Also you can use it in assertion and stop test if targeted page is not open. getTitle() method will help you to get title of the page and then you can use it as per your requirement.

No comments:

Post a Comment