How to Launch Browser in Selenium

Related Product On This Page What is Browser Automation?May 19, 2026 · 15 min read · Tool Comparison

Related Product

How to Launch Browser in Selenium

Launching a browser is the first step in any Selenium automation playscript. However, inconsistent apparatus across different browser can lead to failed tests and wasted effort. Selenium WebDriver direct these issues, make it possible to reliably start and manage different browsers for test.

Overview

Selenium WebDriver let testers to reliably unfastened and control Chrome, Firefox, Edge, and more, ensuring unlined cross-browser testing from the very start.

How to launch browser in Selenium

  1. Install Java Development Kit (JDK): Download and install the latest JDK, then configure the environment variables (JAVA_HOME, PATH).
  2. Install an Integrated Development Environment (IDE): Use an IDE like Eclipse or IntelliJ to indite and manage Selenium test scripts.
  3. Download and Set Up Selenium WebDriver: Add the Selenium WebDriver libraries to your project to interact with browser programmatically.
  4. Download and Set Up ChromeDriver: Get the ChromeDriver viable, gibe it with your Chrome version, and set the path in your script to launch Chrome.

This article explores the fundamentals of browser automation and walks you through everything from prerequisite to found browsers in Selenium, pass incognito session, perform lookup, and even scaling tests on real devices with BrowserStack.

What is Browser Automation?

is the operation of automating the testing of to ensure fast, more true, and quality-rich freeing. It allows testers to interact with browser ingredient and perform actions simply like a existent exploiter.

Among the various tool available, stands out as one of the most widely used fabric, enable teams to amply leverage the benefits of browser automation.

Why is Browser Automation required?

Modern web covering are complex, dynamical, and expected to deliver seamless experiences across browsers, device, and platforms. alone can not proceed pace with frequent releases and rapid development cycles. This is where browser mechanization turn essential.

Browser automation is take because it:

  • Saves time and effortby fulfill repetitious tryout example faster than manual examination.
  • Ensures accuracyby eliminating human errors in test executing.
  • Supports cross-browser examinationto validate functionality and UI across different browsers and versions.
  • Enables faster release cyclesby integrating with for.
  • Improves by running big volumes of that would be Laputan to execute manually.

Read More:

Browser Automation using Selenium Webdriver

Selenium WebDriver allows browser automation, by connecting client to server. There are driver classes for different browsers in Selenium, which implement the Webdriver interface in order to interact with the browser. Here ’ s what happens internally when you instantiate ChromeDriver.

WebDriver driver = new ChromeDriver ();

Here, the ChromeDriver class is initialized, which implements the WebDriver interface.

This ChromeDriver class will interact with the chrome browser to execute the user actions.

As realize in the above diagram, webdriver acts as an interface between client and server.

Also Read:

How to Launch a Browser in Selenium?

When act with Selenium for web automation, one of the initiative tasks is to launch a browser that Selenium will check. Selenium supports various browser, include Chrome, Firefox, Edge, and Safari. Each browser requires its corresponding WebDriver to interact with Selenium.

This guide focalize on launching the Chrome browser employ Selenium. Chrome is a democratic pick for many automation tasks due to its speed and robust developer tools. To start automating with Chrome, you & # 8217; ll need to set up Selenium with ChromeDriver, the WebDriver specifically for Chrome.

Pre-Requisites

There will be two prerequisites for this

  1. Setting up Selenium with the ChromeDriver
  2. Configuring your IDE (for e.g Eclipse IDE for the running the codification)

Setting up Selenium with ChromeDriver in Java involves a series of measure. Here ’ s a detailed guide to aid you through the process:

Step 1: Install Java Development Kit (JDK)

1. Download JDK: Go to theOracle JDK download pageor adopt an open-source version likeOpenJDK.

2. Install JDK: Follow the installation pedagogy specific to your operating system.

3. Set Up Environment Variables:

  • Windows:
    1. Right-click on ‘ This PC ’ or ‘ My Computer ’ and quality ‘ Properties ’.
    2. Click on ‘ Advanced scheme settings ’.
    3. Click on ‘ Environment Variables ’.
    4. Add a new scheme variableJAVA_HOMEand set its value to the itinerary of your JDK installing.
    5. Edit the ‘ Path ’ variable to include% JAVA_HOME % \bin.
  • Mac/Linux:
    1. Open a terminal.
    2. Add export JAVA_HOME=/path/to/your/jdk to your .bashrc or .zshrc file.
    3. Add exportation PATH= $ JAVA_HOME/bin: $ PATHto the same file.
    4. Run source ~/.bashrc or root ~/.zshrcto apply the changes.

Step 2: Install an Integrated Development Environment (IDE)

1. Choose an IDE: Popular choices includeIntelliJ IDEA, Eclipse, or NetBeans.

2. Install the IDE: Download and follow the installation education for your chosen IDE.

Step 3: Download and Set Up Selenium WebDriver

1. Download Selenium: Go to the Selenium website and download the Selenium Java client library.

2. Add Selenium to Your Project:

  • Maven Project: Add the following dependence to yourpom.xml file:
& lt; dependency & gt; & lt; groupId & gt; org.seleniumhq.selenium & lt; /groupId & gt; & lt; artifactId & gt; selenium-java & lt; /artifactId & gt; & lt; version & gt; 4.20.0 & lt; /version & gt; & lt; /dependency & gt;
  • Non-Maven Project: Extract the downloaded Selenium Java client library and add the JAR files to your project ’ s build path.

Step 4: Download and Set Up ChromeDriver

1. Download ChromeDriver:Go to the ChromeDriver download page and download the version that tally your version of Chrome.

2. Extract the ChromeDriver: Extract the downloaded file to a directory of your selection.

3. Set Up ChromeDriver Path:

  • Windows:
    1. Place chromedriver.exein a directory (e.g.,C: \WebDriver).
    2. Add this directory to your scheme ’ s PATH variable.
  • Mac/Linux:
    • Place chromedriverin a directory (e.g.,/usr/local/bin).
    • Ensure the directory is in your PATH.

The below model shows how to launch different browsers like chrome, firefox, IE with the assistant ofWebDriverManager class and properties file.

packet com.qa.browserstack.base; import java.io.FileInputStream; importee java.io.FileNotFoundException; import java.io.IOException; importee java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class BasePage {WebDriver driver; Properties prop; public WebDriver init_driver (Properties airscrew) {String browser = prop.getProperty (`` browser ''); if (browser.equals (`` chrome '')) {WebDriverManager.chromedriver () .setup (); driver = new ChromeDriver ();} else if (browser.equals (`` firefox '')) {WebDriverManager.firefoxdriver () .setup (); driver = new FirefoxDriver ();} else {System.out.println (`` Please cater a proper browser value .. '');} driver.manage () .window () .fullscreen (); driver.manage () .deleteAllCookies (); driver.get (prop.getProperty (`` url '')); render driver;} public Properties init_properties () {prop = new Properties (); try {FileInputStream ip = new FileInputStream (`` Properties file path ''); prop.load (ip);} match (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} revert prop;}}

In this example, the browser value is passed with the assist of the properties file. Depending upon the given value, the specific driver will be instantiated. This is besides a way, using which you can execute cross browser examine across different browsers.

On executing the above code for chrome browser, you can see the browser is launched successfully. Similarly you can found other browser as well.

This code snippet render a structured way to set up and launch a web browser for automated testing with Selenium.

Here & # 8217; s a step-by-step guide on how it works:

1. Create the BasePage Class

  • Purpose: Define a class nameBasePageto handle browser setup and configuration.

2. Declare Instance Variables

  • WebDriver driver: This variable will hold the WebDriver instance that controls the browser.
  • Properties prop: This variable will store configuration item like browser type and URL.

3. Method to Initialize WebDriver

  • Method Name: init_driver (Properties prop)
  • Purpose: Set up the WebDriver based on the browser case specified in the properties register.

a. Retrieve Browser Type

  • Action: Get the browser type from theprop object.
  • Purpose: Determine which browser to launch (Chrome or Firefox).

b. Set Up Browser

  • If Chrome:
    • Action: Use WebDriverManagerto download and set up the ChromeDriver.
    • Create: InstantiateChromeDriverto launch Chrome.
  • If Firefox:
    • Action: Use WebDriverManagerto download and set up the FirefoxDriver.
    • Create: InstantiateFirefoxDriverto launch Firefox.
  • If Not Recognized:
    • Action: Print an error content if the browser character is invalid.

c. Configure the Browser

  • Fullscreen Mode: Set the browser window to fullscreen.
  • Clear Cookies: Remove all cookies to start with a clean slate.
  • Open URL: Navigate to the URL specified in the properties file.

d. Return WebDriver Instance

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

  • Purpose: Return the initialized WebDriver so it can be used for farther actions.

4. Method to Load Properties

  • Method Name: init_properties ()
  • Purpose: Load conformation settings from a properties file.

a. Create Properties Object

  • Action: Initialize a newPropertiesobject to store setting.

b. Load the Properties File

  • Action: Open and read the holding file to load the settings.
  • Error Handling: Catch and mark errors if the file is not found or can not be say.

c. Return Properties Object

  • Purpose: Return the prop aim containing the loaded configuration settings.

Also Read:

How to Open an Incognito Window in Selenium?

While the above method explaining how to launch a browser, this method is utilize when you need to open an Incognito Window in Selenium.

ChromeOptionsclass in Selenium helps to open the browser in incognito mode.

You have to surpassincognitoas an contestation to theaddArguments method of ChromeOptions class.

Let & # 8217; s take the same example as above and walkincognitoas an argument while launching chrome browser

software com.qa.browserstack.base; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; importee org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; meaning org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; importation io.github.bonigarcia.wdm.WebDriverManager; public category BasePage {WebDriver driver; Properties prop; public WebDriver init_driver (Properties prop) {String browser = prop.getProperty (`` browser ''); if (browser.equals (`` chrome '')) {ChromeOptions option = new ChromeOptions (); option.addArguments (`` incognito ''); WebDriverManager.chromedriver () .setup (); driver = new ChromeDriver (option);} else if (browser.equals (`` firefox '')) {WebDriverManager.firefoxdriver () .setup (); driver = new FirefoxDriver ();} else {System.out.println (`` Please provide a proper browser value .. '');} driver.manage () .window () .fullscreen (); driver.manage () .deleteAllCookies (); driver.get (prop.getProperty (`` url '')); return driver;} public Properties init_properties () {property = new Properties (); try {FileInputStream ip = new FileInputStream (`` Properties File Path ''); prop.load (ip);} catch (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} retrovert prop;}}

Chrome browser open in incognito mode as seen below.

Step-by-Step Summary of Browser Initialization Code

Step 1. Create the BasePage Class

  • Purpose: Define a stratum callBasePageto handle the apparatus and shape of the browser for automated testing.

Step 2. Declare Instance Variables

  • WebDriver driver: Stores the WebDriver instance habituate to control the browser.
  • Properties shore: Holds configuration details such as browser type and URL.

Step 3. Method to Initialize WebDriver

  • Method Name: init_driver (Properties property)
  • Purpose: Set up and configure the WebDriver based on the properties provided.

a. Retrieve Browser Type

  • Action: Get the browser case from theprop object.
  • Purpose: Determine which browser to launch (Chrome or Firefox).

b. Set Up Browser

  • If Chrome:
    • Create Options: InstantiateChromeOptionsto configure browser-specific settings.
    • Add Arguments: Add the incognitoargumentation to open Chrome in incognito mode.
    • Set Up Driver: Use WebDriverManagerto download and set up the ChromeDriver.
    • Create Driver: InstantiateChromeDriverwith the configured alternative.
  • If Firefox:
    • Set Up Driver: Use WebDriverManagerto download and set up the FirefoxDriver.
    • Create Driver: InstantiateFirefoxDriverwithout additional options.
  • If Browser Type Is Not Recognized:
    • Action: Print an erroneousness message to bespeak an invalid browser eccentric.

c. Configure the Browser

  • Fullscreen Mode: Set the browser window to fullscreen.
  • Open Cookies: Remove all cookies to start with a clean session.
  • Open URL: Navigate to the URL specified in the property file.

d. Return WebDriver Instance

  • Purpose: Return the initialized and configured WebDriver for use in tests.

Step 4. Method to Load Properties

  • Method Name: init_properties ()
  • Purpose: Load configuration settings from a properties file.

a. Create Properties Object

  • Action: Instantiate a newPropertiesaim to hold the form settings.

b. Load the Properties File

  • Action: Open and read the properties file usingFileInputStream.
  • Error Handling: Catch and mark errors if the file is not found or if there is an issue read it.

c. Return Properties Object

  • Purpose: Return thepropobject curb the ladened conformation background.

Also Read:

How to Open a Page utilize Selenium?

To open a page or site in Selenium, you take to pass the url of the page indriver.get ()method. In this example, the URL is passed through the properties file. Then, use the driver.get () method to access the specify URL.

packet com.qa.browserstack.base; signification java.io.FileInputStream; import java.io.FileNotFoundException; meaning java.io.IOException; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class BasePage {WebDriver driver; Properties prop; public WebDriver init_driver (Properties airscrew) {String browser = prop.getProperty (`` browser ''); if (browser.equals (`` chrome '')) {WebDriverManager.chromedriver () .setup (); driver = new ChromeDriver ();} else if (browser.equals (`` firefox '')) {WebDriverManager.firefoxdriver () .setup (); driver = new FirefoxDriver ();} else {System.out.println (`` Please provide a proper browser value .. '');} driver.get (prop.getProperty (`` url '')); regress driver;} public Properties init_properties () {prop = new Properties (); try {FileInputStream ip = new FileInputStream (`` Properties File Path ''); prop.load (ip);} catch (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} return prop;}}

The above code clearbrowserstack.comURL in Chrome browser as witness in the image below.

1. Define the BasePage Class

  • Purpose: Create a class makeBasePageto manage browser apparatus and conformation for automated testing.

2. Declare Instance Variables

  • WebDriver driver: This variable maintain the WebDriver instance, which is used to control the browser.
  • Properties prop: This varying contains configuration settings, such as the browser type and URL to open.

3. Method to Initialize WebDriver

  • Method Name: init_driver (Properties prop)
  • Purpose: Set up and configure the WebDriver base on the settings cater in the belongings file.

a. Retrieve Browser Type

  • Action: Get the case of browser to use from the property objective.
  • Purpose: Determine which browser (Chrome or Firefox) to launch.

b. Set Up Browser

  • If Chrome:
    • Action: Use WebDriverManagerto automatically download and set up the ChromeDriver.
    • Create: Instantiate aChromeDriverto open Chrome.
  • If Firefox:
    • Action: Use WebDriverManagerto automatically download and set up the FirefoxDriver.
    • Create: Instantiate aFirefoxDriverto open Firefox.
  • If Browser Type Is Not Recognized:
    • Action: Print an error message indicating that an invalid browser type was furnish.

c. Navigate to URL

  • Action: Open the URL fix in the properties file expend
    driver.get (prop.getProperty (& # 8220; url & # 8221;)).
  • Purpose: Direct the browser to the specified web address.

d. Return WebDriver Instance

  • Purpose: Return the configured WebDriver representative for farther use in your test.

4. Method to Load Properties

  • Method Name: init_properties ()
  • Purpose: Load configuration settings from a properties file.

a. Create Properties Object

  • Action: Instantiate a newPropertiesobject to store the configuration data.

b. Load the Properties File

  • Action: Exposed and read the properties file usingFileInputStream.
  • Error Handling: Catch and print errors if the file is not found or if there are issues reading it.

c. Return Properties Object

  • Purpose: Return the airscrew objective containing the loaded form settings.

How to execute Google Search Automation in Selenium

Google Search is widely used by the end-users, and it makes a significant use case for Browser Automation. For any website, it is crucial that users are able to search, find the website in Google SERP (Search Engine Results Page), and click to access the website. This makes it a valid exam case for.

Here ’ s an example of searching “ browserstack ” string in Google to understand Google Search Automation in Selenium.

Whenever you enter a search twine in the google search box, it displays multiple options in suggestions. These suggestions are expose with the assistance of Ajax (Asynchronous javascript and XML). It is a technology used for creating interactive web applications.

You can store these suggestions and choose the suited pick with the help of Selenium.

import java.time.Duration; import java.util.List; importation org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; signification org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class GoogleSearchTest {public static void independent (String [] args) {String Searchstring = `` browserstack ''; WebDriverManager.chromedriver () .setup (); WebDriver driver = new ChromeDriver (); String url = `` https: //www.google.com/ ''; driver.get (url); driver.manage () .window () .maximize (); driver.manage () .timeouts () .implicitlyWait (Duration.ofSeconds (20)); driver.findElement (By.name (`` q '')) .sendKeys (Searchstring); driver.manage () .timeouts () .implicitlyWait (Duration.ofSeconds (20)); List & lt; WebElement & gt; searchitems = driver.findElements (By.xpath (`` //ul [@ role='listbox '] /li/descendant: :div [@ class='eIPGRd '] '')); for (int i=0; i & lt; searchitems.size (); i++) {String listitem = searchitems.get (i) .getText (); System.out.println (listitem); if (listitem.contains (Searchstring)) {searchitems.get (i) .click (); break;}}}}

The above codification searchesbrowserstackstring in the Google Search Box, as seen in the picture below.

In the above code, the list of all suggestions displayed in google lookup is captured employ Selenium and then select the required search string.

Console Output:

Set Up:Import necessary libraries and define theGoogleSearchTest class.

Initialize WebDriver:

  • Set up ChromeDriver habituate WebDriverManager.
  • Create an instance of ChromeDriver to interact with the browser.

Navigate to Google:

  • Open Google & # 8217; s homepage.
  • Maximize the browser window and set an implicit wait.

Perform and Handle Search:

  • Enter the search query into Google ’ s lookup box.
  • Wait for search suggestions to look.
  • Retrieve all search suggestions and print each proffer.
  • Click on the suggestion that matches the search query and stop farther processing.

How to Launch Browser on Real Devices using BrowserStack?

allows us to execute examination on various device-browser combinations which is helpful when the test suites are large and you need to perform to run test cases simultaneously on different device-browser combinations.

Here ’ s an example to launch browser on BrowserStack:

, and get your BrowserStack username and accession key before fulfil the below code.You can get your username and access key once you login to BrowserStack, Navigate to Dashboard and Click on Access Key as shown below.

packet BS; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; importee org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import java.net.URL; public class LaunchBrowserOnBS {public static final String AUTOMATE_USERNAME = `` your_username ''; public static terminal String AUTOMATE_ACCESS_KEY = `` your_password ''; public static final String URL = `` https: // '' + AUTOMATE_USERNAME + ``: '' + AUTOMATE_ACCESS_KEY + `` @ hub-cloud.browserstack.com/wd/hub ''; public electrostatic void main (String [] args) shed Exception {DesiredCapabilities caps = new DesiredCapabilities (); caps.setCapability (`` os_version '', `` 10 ''); caps.setCapability (`` resolution '', `` 1920x1080 ''); caps.setCapability (`` browser '', `` Chrome ''); caps.setCapability (`` browser_version '', `` latest ''); caps.setCapability (`` os '', `` Windows ''); caps.setCapability (`` gens '', `` Test to launch chrome browser on BS ''); // exam name final WebDriver driver = new RemoteWebDriver (new URL (URL), caps); try {// go to bstackdemo.com driver.get (`` https: //www.browserstack.com/ '');} match (Exception e) {// mark any elision System.out.println (e);} // resign the driver driver.quit ();}}

Talk to an Expert

Here ’ s how the Dashboard looks like with all the point like Text Logs, Network Logs, and Video Logs.

BrowserStack Automate Dashboard also contains the details of Input Capabilites and Device Capabilities as find below.

You can play the test that has been performed or even download the test case. BrowserStack supply a wide orbit of capabilities that detail every step in particular along with the time of execution. Using, you can record and playback the Browser Automation examination for best debugging failed tests.

Conclusion

Launching a browser is the foundation of any Selenium mechanisation book, and setting up the correct environment ensures honest and effective test execution. From installing prerequisites to initializing ChromeDriver, each step plays a vital use in enabling smooth browser automation. Beyond local setups, leveraging program like BrowserStack allow teams to run Selenium tests on K of real devices and browsers, ensuring true cross-browser compatibility and faster freeing.

Tags
82,000+ Views

# Ask-and-Contributeabout this subject with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free