How to Run Selenium WebDriver in Different Popular Browsers

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated February 28, 2024

In this tutorial, we have explained how to set up Selenium WebDrivers for the various browsers available in the market:

Selenium only supports web-based applications and to open them we need a browser. It is able to support various browsers for test automation.

In the current industry, there are only three popular browsers which are widely used i.e. Google Chrome, Mozilla Firefox and Internet Explorer. However, Selenium effectively supports other browsers as well. To execute our script on various browsers we need the driver of that browser.

Running Selenium WebDriver in Different Browsers

Selenium Webdriver in different browsers

=> Read all Selenium Tutorials Here

How to Set Up Drivers for Different Browsers

When we first start with Selenium automation, our very first line of code comes as: 

WebDriver driver = new FireFoxDriver ();

WebDriver is an interface and we are defining a reference variable (driver) whose type is an interface.

Now, any object we assign to it must be an instance of a class (FireFoxDriver) or any other driver that implements that interface. In our case, FireFoxDriver is a class and interface is WebDriver.

When all our driver setup is done we execute any Selenium command such as:

driver.getTitle ();

Refer screenshot:

driver

What happens now is that internally an HTTP request is created and sent to the specific browser driver that we defined, the browser driver uses that HTTP server to get the HTTP request and it determines the steps needed for implementing the Selenium command.

Our created logic is executed on the browser, then the execution result is sent back to the HTTP server and it again sends back the status to the automation script.

Thus, after setting up the driver we can access all the in-built methods of driver’s class like:

  • findElement();
  • close();
  • getClass(); and many more

Refer Screenshot:

driver 1

To access these methods, type “driver.” in the editor and it will show you all the methods, or else you can press “ctrl+space” and it will show you the methods.

Refer screenshot:

driver 2

Sometimes built-in methods are not accessible when you press “ctrl+space”. Then you need to check your JAVA_HOME path settings made in Environment Variable and make sure they are correct.

Steps to set up Environment Variable:

  • Go to the Control Panel -> Click System
  • Go to Advanced System Settings
  • Click the Environment Variables button
  • Set JAVA_HOME path on clicking the new button.

Environment Variable

Selenium comes with the default Mozilla Firefox driver, which is bundled in the Selenium WebDriver jar file. That’s why for calling Firefox driver, no setup is required. If we want to use other browsers, we need to set up its system property.

Recommended read => Cross Browser Testing using Selenium Grid

Cross-browser Testing Using Selenium WebDriver

Let us now see the setup and execution of drivers in the below-mentioned browsers:

#1) Mozilla Firefox
#2) Google Chrome
#3) Internet Explorer
#4) Opera
#5) Ghost Driver or PhantomJS
#6) HTML Unit

The drivers for the above-mentioned browsers (except PhantomJS and HTML Unit – check below for these) can be downloaded from here: SeleniumHQ

Assuming you are all aware of the different browsers mentioned above, I will now explain what the Ghost driver and HTML Unit driver functionality are and how to set them up for your script.

#1) HTML Unit Driver

Using this driver we can do Headless Browser Testing which means there is no GUI for it that you can see as it runs internally. Also, you cannot perform all the operations as you do in normal browsers.

Generally, for testing, HTML Unit Driver is not recommended. However, we can use it as it is faster, most lightweight implementation of WebDriver is used for generating test data, to pass the content of one webpage to another program or script.

To use HTML Unit Driver there is no need to install any additional APIs or jar files. You can use it once you have the Selenium server standalone jar file.

Refer below code:

Selenium server standalone jar file

//Create a Java Project, under it create a package, and under package create a class
packageheadless_browser_testing;
import org.openqa.Selenium.WebDriver;
importorg.openqa.Selenium.htmlunit.HtmlUnitDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

publicclassvefifyTestTitle {

//You can run your script with TestNG or JUnit or using Java Application
// I am using TestNG and using TestNG annotations

@Test
publicvoidverifyFacebookTitle() {

//Call HtmlUnit Driver
WebDriver driver = newHtmlUnitDriver(true);

//It will get the Facebook URL and run the script in background, means you
//will not see the Facebook page
driver.get("http://www.facebook.com");

//It will fetch the FB title and store in String
String facebook_Title= driver.getTitle();

//Assert condition will check the expected and actual title, if it matches
//our test passes
Assert.assertTrue(facebook_Title.contains("Facebook"));

System.out.println(facebook_Title);
}
}

Output: Facebook – Log In or Sign Up

PASSED: verifyFacebookTitle

verifyFacebookTitle

HTML Unit driver is not recommended for complex applications and which use jquery, javascript or HTML 5. By default, it does not support javascript. Hence, you have to give the condition truth to support it.

#2) PhantomJS Driver

The PhantomJS browser is also used to perform Headless Browser Testing. It uses a JavaScript API. You can use it for Headless Website Testing and access webpages. It provides one advantage over the HTML Unit Driver and that is capturing screenshots. This means your test will run in the background and will capture the screenshots.

In order to use PhantomJS browser with Selenium WebDriver, we have to use and download GhostDriver. It is an implementation of WebDriver wire protocol in simple JS for PhantomJS browser. Now in the latest release of PhantomJS they have integrated GhostDriver with PhantomJS. Thus, we don’t have to separately install it now.

Download the PhantomJs.exe file from here: PhantomJs

To execute the PhantomJS, we require PhantomJS driver. Download link: PhantomJS driver

We need to set PhantomJs.binary.path property file, when we execute the script.

Refer below code:

PhantomJS driver

//Create a Java Project, then under it create a package, under package create a class
packageheadless_browser_testing;
import java.io.File;
import org.openqa.Selenium.WebDriver;
import org.openqa.Selenium.phantomjs.PhantomJSDriver;
import org.testng.annotations.Test;

publicclass phantom_Js_Driver {
//You can run your script with TestNG or JUnit or using Java Application
// I am using TestNG and using TestNG annotations
 
@Test
publicvoidverifyFacebookTitle() {

//Set the path to access the phantomjs.exe file
File src = newFile("E:\\exe\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe"); 
//You need to specify the property here and give path of driver 
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());

//Call your PhantomJs Driver
WebDriver driver = newPhantomJSDriver();

//It will get the Facebook URL and run the script in background, means you 
//will not see the Facebook page
driver.get("http://www.facebook.com");

//Print the currentURL of the page
System.out.println(driver.getCurrentUrl());
 }
}

Output: https://www.facebook.com/

PASSED: verifyFacebookTitle

PhantomJS code

#3) Mozilla Firefox Driver

How to run WebDriver in Firefox browser:

There is no need to install or configure additional jar files to call Firefox Driver. Selenium WebDriver supports the default driver that Selenium WebDriver supports.

Refer below code for execution:

Firefox Driver

package Different_Drivers;

import org.openqa.Selenium.WebDriver;
import org.openqa.Selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.Assert;

public class FF_Driver {

@Test
public void Test_Gmail_Login() {
WebDriver driver = new FirefoxDriver();
driver.get(“http://www.gmail.com”);
driver.findElement(By.id("Email")).sendKeys("Enter user name");
driver.findElement(By.id("next")).click();
Thread.sleep(2000);
driver.findElement(By.id("Passwd")).sendKeys("Enter Password");
driver.findElement(By.id("signIn")).click();
Thread.sleep(2000);
String title_Of_Page = driver.getTitle();
Assert.assertEquals(driver.getTitle(), title_Of_Page);
System.out.println("Page title matched");
}
}

Output: Page title matched

PASSED: Test_Gmail_Login

Test_Gmail_Login

#4) Google Chrome Driver

How to Run WebDriver in Chrome browser:

To call Google Chrome Driver, first download the driver then make sure to set up the system property using the code below:

system property

package Different_Drivers;
import org.openqa.Selenium.WebDriver;
import org.openqa.Selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
importjava.util.Iterator;
import java.util.Set;

public class googleChrome_Driver {
 
 @Test
public void Test_Rediff_Alert()throws InterruptedException{

//set system property, so that we can access chrome driver
System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");

// It will open the Chrome browser and execute your logic
WebDriverdriver = new ChromeDriver();

//Open rediff page in chrome browser
driver.get(“http://www.rediffmail.com”);

//wait for page to load
Thread.sleep(5000);
// It will get and store the main window page handle or id
 String mainpage = driver.getWindowHandle();
 String subwinhandleString = null;
//set a loop which will store all window pop up handles
 Set<String> handle = driver.getWindowHandles();
 Iterator<String> iterator = handle.iterator();
while(iterator.hasNext ()) {
subwinhandleString = iterator.next( ); 
 }
driver.switchTo().window(subwinhandleString);
System.out.println(driver.getTitle());
Thread.sleep(2000);
driver.close();

//Again switch back to main window
driver.switchTo().window(mainpage);
System.out.println(driver.getTitle());
}
}

Output: Welcome to rediff.com

Rediff.com: Online Shopping, Rediffmail, Latest India News, Business, Bollywood, Sports, Stock, Live Cricket Score, Money, Movie Reviews

PASSED: Test_Rediff_Alert

Test_Rediff_Alert

Also read => Selenium tutorial – Locate Elements in Chrome and IE Browsers

#5) Internet Explorer Driver

How to Run WebDriver in IE browser:

To call Internet Explorer Driver, download the driver and set up a system property.

Refer below code:

driver and set system property

package Different_Drivers;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;

public class  internetExplorer_Driver {

@Test
public void ieDriver() throws InterruptedException {

//set system property, so that we can access IE driver
System.setProperty("webdriver.ie.driver","E\\IEDriverServer.exe");

//set desiredcapabilites for calling ie driver
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability (InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
WebDriver driver = new InternetExplorerDriver(capabilities);

driver.get("https://www.google.com");

Thread.sleep(5000);

String title_Of_Page = driver.getTitle();

System.out.println(title_Of_Page);
}
}

Output: Google

PASSED: ieDriver

ieDriver

#6) Opera Driver

To call Opera Driver, download the driver and set up the system property.

Refer below code:

Opera Driver

package Different_Drivers;
import org.openqa.Selenium.WebDriver;
importorg.openqa.Selenium.opera.OperaDriver;
import org.testng.annotations.Test;
import org.testng.Assert;

public class operaDriver { 
 @Test
public void createAccount(){

//set system property, so that we can access opera driver
System.setProperty("webdriver.opera.driver", "E:\\operadriver.exe");

// it will open the opera browser
WebDriver driver = newOperaDriver();
driver.get("https://www.google.com/intl/en/mail/help/about.html");

 // Here driver will try to find out create an account link on the application
WebElement createAccount = driver.findElement(By.xpath(".//*[@id='gmail-create-account']"));
Assert.assertTrue(createAccount.isDisplayed());
//Create Account will be clicked only if the above condition is true
createAccount.click();
System.out.println(createAccount.getText());
 }
}

Output: Create an account

PASSED: OperaDriver

operaDriver

Also read => TestNG Annotations in Selenium

Conclusion

In this tutorial, I covered how to setup and use drivers for various browsers.

We saw how HTML Unit Driver and PhantomJS Driver are different from other commonly used browsers. The reason behind this difference is that they are not used for common browsing such as Google Chrome and others; instead, they work internally and execute our commands faster as it does not support GUI. We can also perform server-side scripting with PhantomJS.

Now that we understand how to setup drivers and get them working on various browsers, we should also be clear about why we are doing this. As you are all aware, Selenium only supports web-based applications and to open them we need a browser.

There are various drivers (as discussed above) available to open these browsers. A WebDriver is an interface which contains all the abstract methods defined in it. Hence, we call these methods that are discussed in this tutorial to perform our tasks.

Let us know if you have any queries/comments about this tutorial. 

Was this helpful?

Thanks for your feedback!

Recommended Reading

11 thoughts on “How to Run Selenium WebDriver in Different Popular Browsers”

  1. Its not working in case of opera.The following code works fine…
    String operaChromiumDriver =”C:/Program Files/Opera/operadriver.exe”;
    String operaBrowserLocation = “C:/Program Files/Opera/launcher.exe”;

    System.setProperty(“webdriver.opera.driver”, operaChromiumDriver);

    ChromeOptions options = new ChromeOptions();
    options.setBinary(operaBrowserLocation);

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    OperaDriver browser1 = new OperaDriver(capabilities);

    WebDriver driver =browser1;

    Reply
  2. hi
    u explained how to write code for different browsers…but u didn’t explain how to execute code in different browsers one after another or at a time…can u plz post with new article how to excute code on different browsers from testNG

    Reply
  3. Nice details, I would like to learn Selenium from very basics to use it automation tool at out work.

    Any one can suggest me best place to start from ?

    Thanks

    Reply
  4. Hello,

    I am trying to execute selenium script for chrome browser. facing strange problem – syntax error is showing in testng import statement – although all is written correct kindly check.
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.Test;
    importjava.util.Iterator;
    import java.util.Set;

    public class ChromeDrv {
    @Test
    public void test () {

    System.setProperty(“webdriver.chrome.driver”, “C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe”);
    WebDriver driver ;
    driver = new ChromeDriver();
    driver.get(“http://www.rediff.com”);
    Thread.sleep(5000);
    System.out.println(driver.getTitle());
    driver.close();
    }
    }

    Reply
  5. Hello

    I Want To Internet Explorer automation In C# And Open Internet Explorer 32 Bit In 64 Bit OS..
    I run C# Selenium Code Proper Work In Console Application But When I Use In Web Form On Button Click Event IEDriverServer Run In Background Process But Not Run Properly..

    Kindly Give Me Solution

    Thanks In Advance

    Reply
  6. Very useful article for who wants learn how to run selenium webdriver in all browsers but the title you is how to run selenium webdriver in multiple browsers,for that you said grid is a method to run the script in all multiple browsers and my doubt is please give me a answer how to create grid

    Reply
  7. Hello,

    I am trying to execute selenium script for chrome browser.
    Exception in thread “main” java.lang.IllegalStateException: The driver executable does not exist: E:\New folder\1\testchromeE:\New folder\1\testchrome\chromedriver\chromedriver.exe
    at com.google.common.base.Preconditions.checkState(Preconditions.java:534)
    at org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:136)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:131)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:329)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:123)
    at login3.main(login3.java:15)

    i am not getting the error, plz help me out.

    Reply
  8. Hi..recently i started selenium webdriver as a fresher..i faced on issue in that..can you please help me..

    Scenario:
    Iam launching chrome browser – In that i need to submit the Form multiple times.(i need to repeat the same steps)

    kindly give me the solution pls..

    Thanks in Advance..

    Reply

Leave a Comment