Selenium First Script
Writing Your First Selenium Script
Now that we have completed the setup, let's write our first Selenium script and execute it in Chrome browser. We will follow the steps below:- Create a New Project: Open Eclipse and create a new Java project.
- Add Selenium Libraries: then Add the Selenium Java libraries to your project.
- Write the Script: Create a new Java
class and write the following code:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class FirstSeleniumScript { public static void main(String[] args) { // Set the path of the ChromeDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); // Initialize WebDriver WebDriver driver = new ChromeDriver(); // Open a website driver.get("https://nicetesters.com"); // Print the title of the page System.out.println("Title: " + driver.getTitle()); // Close the browser driver.quit(); } }
- Run the Script: To Execute the script, right click on the class and
then find
Run as
option in eclipse and thenJava Application
.
Explanation
Let's go through the code line by line:
- Import Statements:
These lines import the necessary classes from the Selenium library. Likeimport org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;
WebDriver
class is the main interface for testing web applications. And,ChromeDriver
is a class that implements theWebDriver
interface for the Chrome browser. So we need to import these classes. - Class Declaration:
This line declares a public class named FirstSeleniumScript.public class FirstSeleniumScript {
- Main Method:
This line declares the Java main method, which is the entry point of any Java application. This method will be executed by Java without calling it.public static void main(String[] args) {
- Set the Path of the ChromeDriver:
This line sets the system property for the ChromeDriver file. We need to replaceSystem.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
"path/to/chromedriver"
with the actual path to the ChromeDriver file on your system. - Initialize WebDriver:
This line creates an java object of the ChromeDriver, which launches a new Chrome browser window.WebDriver driver = new ChromeDriver();
- Open a Website:
This line navigates the browser to the specified URL (driver.get("https://nicetesters.com");
https://nicetesters.com
) and open the webpage. - Print the Title of the Page:
This line fetch the title of the current page and prints it to the console.System.out.println("Title: " + driver.getTitle());
- Close the Browser:
This line closes the browser and ends the WebDriver session.driver.quit();
Next we will learn Selenium important classes.