WebDriver Methods

Selenium WebDriver provides set of methods to interact with browser. Most commonly used methods are explained below : –

Get Method
get(String url) – opens URL on web page.

driver.get("http://automate-apps.com/");

=================================================================

Get Current URL
getCurrentUrl() – Returns URL of a webpage which is opened in current browser.

driver.get("http://automate-apps.com/");
System.out.println(driver.getCurrentUrl());

=================================================================

Get Page Title
getTitle() – Returns title of the current webpage.

driver.get("http://automate-apps.com/");
System.out.println(driver.getTitle());

=================================================================

Get Page Source
getPageSource() – Returns source(HTML code) of webpage currently opened in a browser.

driver.get("http://automate-apps.com/");
System.out.println(driver.getPageSource());

=================================================================

Close Method
close() – Closes the current browser or page currently which is having the focus.

driver.close(); 

=================================================================

Quit Method
quit() – It is used to destroy the web driver instance. Means it will close all browsers associated with driver session.

driver.quit();

=================================================================

Refer below Sample Program :-

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class Sample {
	
  public static WebDriver driver;
  public static String baseUrl;
  
  public static void main(String s[]) {
       //Initialize driver instance
       driver = new FirefoxDriver();
       baseUrl = "http://www.gmail.com";
	    
       //Launch Application on browser 
       driver.get(baseUrl);
	  
       //Fetch page title and store it in a variable 
       String pageTitle = driver.getTitle();
       //Print title
       System.out.println(pageTitle);
	  
       //Get current url and store it in a variable 
       String currentUrl = driver.getCurrentUrl();
       //Print current URL
       System.out.println(currentUrl);
	  
      //Get page source and store it in a variable 	
      String pageSource = driver.getPageSource(); 
      //Print Page Source
      System.out.println(pageSource);
	  
      //close browser
      driver.close();	    
  }
 
}

If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.

Leave a Reply

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