- Selenium Tutorial
- Selenium - Home
- Selenium - Overview
- Selenium - Components
- Selenium - Automation Testing
- Selenium - Environment Setup
- Selenium - Remote Control
- Selenium IDE Tutorial
- Selenium - IDE Introduction
- Selenium - Features
- Selenium - Limitations
- Selenium - Installation
- Selenium - Creating Tests
- Selenium - Creating Script
- Selenium - Store Variables
- Selenium - Alerts & Popups
- Selenium - Selenese Commands
- Selenium - Actions Commands
- Selenium - Accessors Commands
- Selenium - Assertions Commands
- Selenium - Assert/Verify Methods
- Selenium - Locating Strategies
- Selenium - Script Debugging
- Selenium - Verification Points
- Selenium - Pattern Matching
- Selenium - JSON Data File
- Selenium - Browser Execution
- Selenium - User Extensions
- Selenium - Code Export
- Selenium - JavaScript Functions
- Selenium - Plugins
- Selenium WebDriver Tutorial
- Selenium - Introduction
- Selenium WebDriver vs RC
- Selenium - Installation
- Selenium - First Test Script
- Selenium - Driver Sessions
- Selenium - Browser Options
- Selenium - Chrome Options
- Selenium - Edge Options
- Selenium - Firefox Options
- Selenium - Safari Options
- Selenium Web Elements
- Selenium - File Upload
- Selenium - Locator Strategies
- Selenium - Relative Locators
- Selenium - Finders
- Selenium - Find All Links
- Selenium - User Interactions
- Selenium - WebElement Commands
- Selenium - Browser Interactions
- Selenium - Browser Commands
- Selenium - Browser Navigation
- Selenium - Alerts & Popups
- Selenium - Handling Forms
- Selenium - Windows and Tabs
- Selenium - Handling Links
- Selenium - Input Boxes
- Selenium - Radio Button
- Selenium - Checkboxes
- Selenium - Dropdown Box
- Selenium - Handling IFrames
- Selenium - Handling Cookies
- Selenium - Date Time Picker
- Selenium - Dynamic Web Tables
- Selenium - Actions Class
- Selenium - Action Class
- Selenium - Keyboard Events
- Selenium - Key Up/Down
- Selenium - Copy and Paste
- Selenium - Handle Special Keys
- Selenium - Mouse Events
- Selenium - Drag and Drop
- Selenium - Scroll Operations
- Selenium - Waiting Strategies
- Selenium - Explicit/Implicit Wait
- Selenium - Support Features
- Selenium - Multi Select
- Selenium - Wait Support
- Selenium - Select Support
- Selenium - Color Support
- Selenium - Errors & Logging
- Selenium - Logging
- Selenium - Exception Handling
- Selenium - Miscellaneous
- Selenium - Handling Ajax Calls
- Selenium - JSON Data File
- Selenium - CSV Data File
- Selenium - Excel Data File
- Selenium - Cross Browser Testing
- Selenium - Multi Browser Testing
- Selenium - Multi Windows Testing
- Selenium - JavaScript Executor
- Selenium - Headless Execution
- Selenium - Capture Screenshots
- Selenium - Capture Videos
- Selenium - Page Object Model
- Selenium - Page Factory
- Selenium - Record & Playback
- Selenium - Frameworks
- Selenium - Browsing Context
- Selenium Grid Tutorial
- Selenium - Overview
- Selenium - Architecture
- Selenium - Components
- Selenium - Configuration
- Selenium - Create Test Script
- Selenium - Test Execution
- Selenium - Endpoints
- Selenium - Customizing a Node
- Selenium Reporting Tools
- Selenium - Reporting Tools
- Selenium - TestNG
- Selenium - JUnit
- Selenium - Allure
- Selenium & other Technologies
- Selenium - Java Tutorial
- Selenium - Python Tutorial
- Selenium - C# Tutorial
- Selenium - Javascript Tutorial
- Selenium - Kotlin Tutorial
- Selenium - Ruby  Tutorial
- Selenium - Maven & Jenkins
- Selenium - Database Testing
- Selenium - LogExpert Logging
- Selenium - Log4j Logging
- Selenium - Robot Framework
- Selenium - AutoIT
- Selenium - Flash Testing
- Selenium - Apache Ant
- Selenium - Github
- Selenium - SoapUI
- Selenium - Cucumber
- Selenium - IntelliJ
- Selenium - XPath
- Selenium Miscellaneous Concepts
- Selenium - Automation Frameworks
- Selenium - Keyword Driven Framework
- Selenium - Data Driven Framework
- Selenium - Hybrid Driven Framework
- Selenium - SSL Certificate Error
- Selenium - Alternatives
- Selenium Useful Resources
- Selenium - Quick Guide
- Selenium - Useful Resources
- Selenium - Automation Practice
- Selenium - Discussion
Selenium Webdriver - First Test Script
Before starting with our first test script on Selenium, we should ensure that Java, and Maven have been installed in our system. We can confirm Java installation by running the command: java, from the command prompt.
C:\java
It will display the following information on the screen −
Usage: java [options] <mainclass> [args...] (to execute a class) or java [options] -jar <jarfile> [args...] (to execute a jar file) or java [options] -m <module>[/<mainclass>] [args...] java [options] --module <module>[/<mainclass>] [args...] (to execute the main class in a module) or java [options] <sourcefile> [args] (to execute a single source-file program) Arguments following the main class, source file, -jar <jarfile>, -m or --module <module>/<mainclass> are passed as the arguments to main class. where options include: -cp <class search path of directories and zip/jar files> -classpath <class search path of directories and zip/jar files> --class-path <class search path of directories and zip/jar files> A ; separated list of directories, JAR archives, and ZIP archives to search for class files. -p <module path> --module-path <module path>... A ; separated list of directories, each directory is a directory of modules. --upgrade-module-path <module path>... A ; separated list of directories, each directory is a directory of modules that replace upgradeable modules in the runtime image --add-modules <module name>[,<module name>...] root modules to resolve in addition to the initial module. <module name> can also be ALL-DEFAULT, ALL-SYSTEM, ALL-MODULE-PATH. --enable-native-access <module name>[,<module name>...] modules that are permitted to perform restricted native operations. <module name> can also be ALL-UNNAMED. --list-modules list observable modules and exit -d <module name> --describe-module <module name> describe a module and exit --dry-run create VM and load main class but do not execute main method. The --dry-run option may be useful for validating the command-line options such as the module system configuration. --validate-modules validate all modules and exit The --validate-modules option may be useful for finding conflicts and other errors with modules on the module path. -D<name>=<value> set a system property -verbose:[class|module|gc|jni] enable verbose output for the given subsystem -version print product version to the error stream and exit --version print product version to the output stream and exit -showversion print product version to the error stream and continue --show-version print product version to the output stream and continue --show-module-resolution show module resolution output during startup -? -h -help print this help message to the error stream --help print this help message to the output stream -X print help on extra options to the error stream --help-extra print help on extra options to the output stream -ea[:<packagename>...|:<classname>] -enableassertions[:<packagename>...|:<classname>] enable assertions with specified granularity -da[:<packagename>...|:<classname>] -disableassertions[:<packagename>...|:<classname>] disable assertions with specified granularity -esa | -enablesystemassertions enable system assertions -dsa | -disablesystemassertions disable system assertions -agentlib:<libname>[=<options>] load native agent library <libname>, e.g. -agentlib:jdwp see also -agentlib:jdwp=help -agentpath:<pathname>[=<options>] load native agent library by full pathname -javaagent:<jarpath>[=<options>] load Java programming language agent, see java.lang.instrument -splash:<imagepath> show splash screen with specified image HiDPI scaled images are automatically supported and used if available. The unscaled image filename, e.g. image.ext, should always be passed as the argument to the -splash option. The most appropriate scaled image provided will be picked up automatically. See the SplashScreen API documentation for more information @argument files one or more argument files containing options --disable-@files prevent further argument file expansion --enable-preview allow classes to depend on preview features of this release To specify an argument for a long option, you can use --<name>=<value> or --<name> <value>.
Next, we would confirm the version of the Java installed by running the command −
java –version
It will show the following output −
openjdk version "17.0.9" 2023-10-17 OpenJDK Runtime Environment Homebrew (build 17.0.9+0) OpenJDK 64-Bit Server VM Homebrew (build 17.0.9+0, mixed mode, sharing)
The output of the command executed signified that the java version installed in the system is 17.0.9.
Next, we would confirm the version of the Maven installed by running the command −
mvn –version
It will show the following output −
Apache Maven 3.9.6 (bc0240f3c744dd6b6ec2920b3cd08dcc295161ae) Maven home: /opt/homebrew/Cellar/maven/3.9.6/libexec Java version: 21.0.1, vendor: Homebrew, runtime: /opt/homebrew/Cellar/openjdk/21.0.1/libexec/openjdk.jdk/Contents/Home Default locale: en_IN, platform encoding: UTF-8 OS name: "mac os x", version: "14.0", arch: "aarch64", family: "mac"
The output of the command executed signified that the Maven version installed in the system is Apache Maven 3.9.6.
First of all, we would initiate a driver session and perform some activity on the browser, say launching an web page on the Chrome browser with the help of the below code −
Webdriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");
In the following step, we would retrieve some information about the current URL that is launched on the Chrome browser with the help of the getCurrentUrl() method.
Syntax
driver.getCurrentUrl();
We would also add some synchronization techniques so that the interactions between the Selenium tool and browser actions would be in sync. There are several synchronization methods available in Selenium, like the implicit, explicit, and fluent waits.
While implicit wait is a kind of global wait(applicable to all the steps in a text case), explicit and fluent waits are applied to a specific element on the browser. For our first test script here, we would only apply an implicit wait.
Syntax to add an implicit wait of 15 seconds −
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
To perform any task on a webelement in the Selenium session, we would need to identify the element uniquely with the help of any of the Selenium locators like id, name, class, tagname, link text, partial link text, xpath, and css selector along with findElement() method. If there are multiple elements with the same value of locator, only the first matching element should be identified.
Syntax to identify an element with xpath locator −
WebElement e = driver.findElement(By.xpath("<value of xpath>"));
Next, we would perform a task on the element identified on the previous step using the sendKeys() method. The value to enter is passed as an argument to the method.
Syntax
e.sendKeys("Selenium");
Then, we would request the information on the value entered on input box using the getAttribute() method and value is passed as an argument to the method.
Syntax
String text = driver.findElement(By.xpath("<value of xpath>")).getAttribute("value");
Then, we would wipe out the text entered with the clear() method.
Syntax
e.clear();
Then, we would again request the information on the value on the input box using the getAttribute() method(to prove there is no value within the input box after using the clear() method) and value is passed as an argument to the method.
Syntax
String text = driver.findElement(By.xpath("<value of xpath>")).getAttribute("value");
Finally, we would terminate the driver session using the quit() method which would also close the opened browser window.
Syntax
driver.quit();
Let us now discuss the identification of an input box on a webpage shown in the below image. First, we would need to right click on the webpage, and then click on the Inspect button in the Chrome browser. Then, the corresponding HTML code for the whole page would be visible. For investigating a single element on a page, we would need to click on the left upward arrow, available to the top of the visible HTML code as highlighted below.
Once we had clicked and pointed the arrow to the input box(highlighted in the below image), its HTML code was visible, both reflecting the input tagname(enclosed in <>).
<input id="fullname" name="fullname" type="text" class="form-control" placeholder="Full Name">
Let us take an example of the above page, where we would first enter some text in the input box with the help of the sendKeys() method. The value to enter is passed as an argument to the method. Then, we would wipe out the text entered with the clear() method.
Syntax
Webdriver driver = new ChromeDriver(); driver.findElement(By.xpath("value of xpath")).sendKeys("value entered"); driver.findElement(By.xpath("value of xpath")).clear();
Example
Code Implementation on FrstJavaTestScript.java class file.
package org.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class FrstJavaTestScript { public static void main(String[] args) throws InterruptedException { // Initiate the Webdriver WebDriver driver = new ChromeDriver(); // adding implicit wait of 15 secs driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); // Opening the webpage where we will identify edit box to enter driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php"); // getting current URL System.out.println("Getting the Current URL: " + driver.getCurrentUrl()); // Identify the input box with xpath locator WebElement e = driver.findElement(By.xpath("//*[@id='fullname']")); // enter text in input box e.sendKeys("Selenium"); // Get the value entered String text = e.getAttribute("value"); System.out.println("Entered text is: " + text); // clear the text entered e.clear(); // Get no text after clearing text String text1 = e.getAttribute("value"); System.out.println("Get text after clearing: " + text1); // Closing browser driver.quit(); } }
Output
Getting the Current URL: https://www.tutorialspoint.com/selenium/practice/text-box.php Entered text is: Selenium Get text after clearing: Process finished with exit code 0
In the above example, we had first obtained the current browser title with the message in the console: Getting the Current URL: https://www.tutorialspoint.com/selenium/practice/text-box.php. Then we had entered the text Selenium in the input box, and also retrieved the value entered in the console with the message- Entered text is: Selenium. Next, we had cleared the value entered and no value existed in the input box after clearing up the text. Hence, we had also received the message in the console: Get text after clearing:.
Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.
Thus, in this tutorial, we had discussed how to create the first test script using the Selenium Webdriver.