Friday, July 31, 2015

Working With Chrome Profile With Selenium WebDriver

Previously we learn how to create Firefox Profile and how to access this profile using Selenium WebDriver.
Here We learn how to create Chrome profile and use this profile from Selenium WebDriver.

1. Create Chrome Profile :
  •  Open Chrome Browser and click on Setting option.
  • Scroll down the page and click on Add person option.Give a name and click on Add button. If we check this option"Create a desktop shortcut for the user" then we can find a chrome shortcut for this profile.
  • After creation this profile we can find that a folder created under "Documents and Settings\Administrator\Local Settings\Application Data\Google\Chrome\User Data"
     
2. Accessing Chrome Profile Using Selenium WebDriver :
  • Download Chrome Driver from here .
  • Extact the .exe file from downloaded zip and put this file(.exe) in our project folder.
  • Add this .exe to System property using 
    System.setProperty("webdriver.chrome.driver", "./chromedriver.exe");
                                                         Or

    Using ChromeDriverService class for this.
    ChromeDriverService chSvc = new ChromeDriverService.Builder()
              .usingDriverExecutable(new File("./chromedriver.exe")).usingAnyFreePort().build();

  • Create ChromeOption object and add use addArguments() method to set the user profile.
         ChromeOptions chOption = new ChromeOptions();
         chOption.addArguments("user-data-dir=ChromeProfile Location");

  • Now pass ChromeDriverService and ChromeOption object during ChromeDriver object creation.
            WebDriver driver = new ChromeDriver(chSvc,chOption); 
Example Code: 

package chromeprofile;

import java.io.File;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;

public class LoadChromeProfile {

    public static void main(String[] args) {
        //System.setProperty("webdriver.chrome.driver", "./chromedriver.exe");

        ChromeDriverService chSvc = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File("./chromedriver.exe")).usingAnyFreePort().build();

        ChromeOptions chOption = new ChromeOptions();

        /**
         * "user-data-dir = profilepath" --to open profile
         * "--start-maximized" for maximize the browser
         */

        chOption.addArguments("user-data-dir = Our Profile Path");
        chOption.addArguments("--start-maximized");        WebDriver driver = new ChromeDriver(chSvc, chOption);
        driver.quit();
    }
}