How to Create WebDriver Instance in Selenium: Simple Guide
To create a
WebDriver instance in Selenium, you first import the driver class for your browser (like ChromeDriver), then create an object of that class using new ChromeDriver(). This object controls the browser during your automated tests.Syntax
Creating a WebDriver instance involves importing the browser driver class and initializing it. For example, for Chrome:
- Import: Import the
ChromeDriverclass from Selenium. - Instantiate: Use
new ChromeDriver()to create the driver object. - Assign: Store the object in a
WebDrivervariable to control the browser.
java
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Test { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); } }
Example
This example shows how to create a Chrome WebDriver instance, open a website, and then close the browser.
java
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class OpenGoogle { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); // Create WebDriver instance for Chrome WebDriver driver = new ChromeDriver(); // Open Google homepage driver.get("https://www.google.com"); // Print page title System.out.println("Page title is: " + driver.getTitle()); // Close the browser driver.quit(); } }
Output
Page title is: Google
Common Pitfalls
Common mistakes when creating a WebDriver instance include:
- Not setting the browser driver executable path, which causes errors.
- Using the wrong driver class for the browser.
- Not closing the driver properly, leaving browser windows open.
Always ensure the driver executable (like chromedriver) is in your system PATH or set via System.setProperty.
java
/* Wrong way: Missing driver path setup */ // WebDriver driver = new ChromeDriver(); // This may fail if chromedriver path is not set /* Right way: Set driver path before creating instance */ System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver();
Quick Reference
Remember these key points when creating a WebDriver instance:
- Import the correct driver class for your browser.
- Set the driver executable path if needed.
- Instantiate the driver with
new. - Use the driver object to control the browser.
- Close the driver with
quit()after tests.
Key Takeaways
Always import and instantiate the correct browser driver class to create a WebDriver instance.
Set the browser driver executable path before creating the WebDriver to avoid errors.
Use the WebDriver object to open URLs and control the browser.
Close the WebDriver with quit() to free resources and close the browser.
Check your browser and driver versions for compatibility.