FREE Online Selenium Tutorial for beginners in Java - Learn Selenium WebDriver automation step by step hands-on practical examples Skip to content Tussen de Vaarten, Almere, 1318PG (Netherlands) +04 email protected. Selenium is a popular open-source web-based automation tool. This online course is a step by step guide to learn Selenium Concepts. It is recommended you refer the tutorials sequentially, one after the other. This free tutorial is designed for beginners with little or no automation experience.
Using the Java class 'myclass' that we created in the previous tutorial, let us try to create a WebDriver script that would:
- fetch Mercury Tours' homepage
- verify its title
- print out the result of the comparison
- close it before ending the entire program.
WebDriver Code
Below is the actual WebDriver code for the logic presented by the scenario above
Note: Starting Firefox 35, you need to use gecko driver created by Mozilla to use Web Driver. Selenium 3.0, gecko and firefox has compatibility issues and setting them correctly could become an uphill task. If the code does not work, downgrade to Firefox version 47 or below. Alternatively, you can run your scripts on Chrome. Selenium works out of the box for Chrome. You just need to change 3 lines of code to make your script work with Chrome or Firefox
Explaining the code
Importing Packages
To get started, you need to import following two packages:
- org.openqa.selenium.*- contains the WebDriver class needed to instantiate a new browser loaded with a specific driver
- org.openqa.selenium.firefox.FirefoxDriver - contains the FirefoxDriver class needed to instantiate a Firefox-specific driver onto the browser instantiated by the WebDriver class
If your test needs more complicated actions such as accessing another class, taking browser screenshots, or manipulating external files, definitely you will need to import more packages.
Instantiating objects and variables
Normally, this is how a driver object is instantiated.
A FirefoxDriver class with no parameters means that the default Firefox profile will be launched by our Java program. The default Firefox profile is similar to launching Firefox in safe mode (no extensions are loaded).
For convenience, we saved the Base URL and the expected title as variables.
Launching a Browser Session
WebDriver's get() method is used to launch a new browser session and directs it to the URL that you specify as its parameter.
Get the Actual Page Title
The WebDriver class has the getTitle() method that is always used to obtain the page title of the currently loaded page.
Create yahoo email account free. A premium account includes, among other features, the possibility to forward your mails to another email address via POP3/IMAP.
Compare the Expected and Actual Values
This portion of the code simply uses a basic Java if-else structure to compare the actual title with the expected one.
Terminating a Browser Session
The 'close()' method is used to close the browser window.
Terminating the Entire Program
If you use this command without closing all browser windows first, your whole Java program will end while leaving the browser window open.
Running the Test
There are two ways to execute code in Eclipse IDE.
- On Eclipse's menu bar, click Run > Run.
- Press Ctrl+F11 to run the entire code.
If you did everything correctly, Eclipse would output 'Test Passed!'
Locating GUI Elements
Locating elements in WebDriver is done by using the 'findElement(By.locator())' method. The 'locator' part of the code is same as any of the locators previously discussed in the Selenium IDE chapters of these tutorials. Infact, it is recommended that you locate GUI elements using IDE and once successfully identified export the code to webdriver.
Here is a sample code that locates an element by its id. Facebook is used as the Base URL.
We used the getTagName() method to extract the tag name of that particular element whose id is 'email'. When run, this code should be able to correctly identify the tag name 'input' and will print it out on Eclipse's Console window.
Summary for locating elementsVariation | Description | Sample |
---|---|---|
By.className | finds elements based on the value of the 'class' attribute | findElement(By.className('someClassName')) |
By.cssSelector | finds elements based on the driver's underlying CSS Selector engine | findElement(By.cssSelector('input#email')) |
By.id | locates elements by the value of their 'id' attribute | findElement(By.id('someId')) |
By.linkText | finds a link element by the exact text it displays | findElement(By.linkText('REGISTRATION')) |
By.name | locates elements by the value of the 'name' attribute | findElement(By.name('someName')) |
By.partialLinkText | locates elements that contain the given link text | findElement(By.partialLinkText('REG')) |
By.tagName | locates elements by their tag name | findElement(By.tagName('div')) |
By.xpath | locates elements via XPath | findElement(By.xpath('//html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/ form/table/tbody/tr[5]')) |
Note on Using findElement(By.cssSelector())
By.cssSelector() does not support the 'contains' feature. Consider the Selenium IDE code below -
https://ninworldof.netlify.app/adobe-flash-player-ubuntu-firefox.html. Cd /home/user/Downloads). In the Terminal window, change to the directory where you saved the file you downloaded (e.g.
In Selenium IDE above, the entire test passed. However in the WebDriver script below, the same test generated an error because WebDriver does not support the 'contains' keyword when used in the By.cssSelector() method.
Common Commands
Instantiating Web Elements
Instead of using the long 'driver.findElement(By.locator())' syntax every time you will access a particular element, we can instantiate a WebElement object for it. The WebElement class is contained in the 'org.openqa.selenium.*' package.
Clicking on an Element
Clicking is perhaps the most common way of interacting with web elements. The click() method is used to simulate the clicking of any element. The following example shows how click() was used to click on Mercury Tours' 'Sign-In' button.
Following things must be noted when using the click() method.
- It does not take any parameter/argument.
- The method automatically waits for a new page to load if applicable.
- The element to be clicked-on, must be visible (height and width must not be equal to zero).
Get Commands
Get commands fetch various important information about the page/element. Here are some important 'get' commands you must be familiar with.get()Sample usage: |
|
getTitle()Sample usage: |
|
getPageSource()Sample usage: |
|
getCurrentUrl()Sample usage: |
|
getText()Sample usage: |
|
Navigate commands
These commands allow you to refresh,go-into and switch back and forth between different web pages.navigate().to()Sample usage: |
|
navigate().refresh()Sample usage: |
|
navigate().back()Sample usage: |
|
navigate().forward()Sample usage: |
|
Closing and Quitting Browser Windows
close()Sample usage: |
|
quit()Sample usage: |
|
To clearly illustrate the difference between close() and quit(), try to execute the code below. It uses a webpage that automatically pops up a window upon page load and opens up another after exiting.
Notice that only the parent browser window was closed and not the two pop-up windows.
But if you use quit(), all windows will be closed - not just the parent one. Try running the code below and you will notice that the two pop-ups above will automatically be closed as well.
Switching Between Frames
To access GUI elements in a Frame, we should first direct WebDriver to focus on the frame or pop-up window first before we can access elements within them. Let us take, for example, the web page http://demo.guru99.com/selenium/deprecated.html
This page has 3 frames whose 'name' attributes are indicated above. We wish to access the 'Deprecated' link encircled above in yellow. In order to do that, we must first instruct WebDriver to switch to the 'classFrame' frame using the 'switchTo().frame()' method. We will use the name attribute of the frame as the parameter for the 'frame()' part.
After executing this code, you will see that the 'classFrame' frame is taken to the 'Deprecated API' page, meaning that our code was successfully able to access the 'Deprecated' link.
Switching Between Pop-up Windows
WebDriver allows pop-up windows like alerts to be displayed, unlike in Selenium IDE. To access the elements within the alert (such as the message it contains), we must use the 'switchTo().alert()' method. In the code below, we will use this method to access the alert box and then retrieve its message using the 'getText()' method, and then automatically close the alert box using the 'switchTo().alert().accept()' method.
First, head over to http://jsbin.com/usidix/1 and manually click the 'Go!' button there and see for yourself the message text.
https://ninworldof.netlify.app/flash-subtitles-download.html. Lets see the WebDriver code to do this-
On the Eclipse console, notice that the printed alert message is:
Waits
There are two kinds of waits.
- Implicit wait - used to set the default waiting time throughout the program
- Explicit wait - used to set the waiting time for a particular instance only
Implicit Wait
- It is simpler to code than Explicit Waits.
- It is usually declared in the instantiation part of the code.
- You will only need one additional package to import.
To start using an implicit wait, you would have to import this package into your code.
Then on the instantiation part of your code, add this.
Explicit Wait
Explicit waits are done using the WebDriverWait and ExpectedCondition classes. For the following example, we shall wait up to 10 seconds for an element whose id is 'username' to become visible before proceeding to the next command. Here are the steps.
Step 1
Import these two packages:
Step 2
Declare a WebDriverWait variable. In this example, we will use 'myWaitVar' as the name of the variable.
Step 3
Use myWaitVar with ExpectedConditions on portions where you need the explicit wait to occur. In this case, we will use explicit wait on the 'username' (Mercury Tours HomePage) input before we type the text 'tutorial' onto it.
Conditions
Following methods are used in conditional and looping operations --
- isEnabled() is used when you want to verify whether a certain element is enabled or not before executing a command.
- isDisplayed() is used when you want to verify whether a certain element is displayed or not before executing a command.
- isSelected() is used when you want to verify whether a certain check box, radio button, or option in a drop-down box is selected. It does not work on other elements.
Using ExpectedConditions
The ExpectedConditions class offers a wider set of conditions that you can use in conjunction with WebDriverWait's until() method.
Below are some of the most common ExpectedConditions methods.
- alertIsPresent() - waits until an alert box is displayed.
Selenium Webdriver Tutorial Java
- elementToBeClickable() - Waits until an element is visible and, at the same time, enabled. The sample code below will wait until the element with to become visible and enabled first before assigning that element as a WebElement variable named 'txtUserName'.
- frameToBeAvailableAndSwitchToIt() - Waits until the given frame is already available, and then automatically switches to it.
Catching Exceptions
Selenium Webdriver Page Object Example Java
When using isEnabled(), isDisplayed(), and isSelected(), WebDriver assumes that the element already exists on the page. Otherwise, it will throw a NoSuchElementException. To avoid this, we should use a try-catch block so that the program will not be interrupted.
If you use explicit waits, the type of exception that you should catch is the 'TimeoutException'.
Selenium Webdriver Example Java Free
- To start using the WebDriver API, you must import at least these two packages.
- org.openqa.selenium.*
- org.openqa.selenium.firefox.FirefoxDriver
- The get() method is the equivalent of Selenium IDE's 'open' command.
- Locating elements in WebDriver is done by using the findElement() method.
- The following are the available options for locating elements in WebDriver:
- By.className
- By.cssSelector
- By.id
- By.linkText
- By.name
- By.partialLinkText
- By.tagName
- By.xpath
- The By.cssSelector() does not support the 'contains' feature.
- You can instantiate an element using the WebElement class.
- Clicking on an element is done by using the click() method.
- WebDriver provides these useful get commands:
- get()
- getTitle()
- getPageSource()
- getCurrentUrl()
- getText()
- WebDriver provides these useful navigation commands
- navigate().forward()
- navigate().back()
- navigate().to()
- navigate().refresh()
- The close() and quit() methods are used to close browser windows. Close() is used to close a single window; while quit() is used to close all windows associated to the parent window that the WebDriver object was controlling.
- The switchTo().frame() and switchTo().alert() methods are used to direct WebDriver's focus onto a frame or alert, respectively.
- Implicit waits are used to set the waiting time throughout the program, while explicit waits are used only on specific portions.
- You can use the isEnabled(), isDisplayed(),isSelected(), and a combination of WebDriverWait and ExpectedConditions methods when verifying the state of an element. However, they do not verify if the element exists.
- When isEnabled(), isDisplayed(),or isSelected() was called while the element was not existing, WebDriver will throw a NoSuchElementException.
- When WebDriverWait and ExpectedConditions methods were called while the element was not existing, WebDriver would throw a TimeoutException.
Note:
driver.get() : It's used to go to the particular website , But it doesn't maintain the browser History and cookies so , we can't use forward and backward button , if we click on that , page will not get schedule
driver.navigate() : it's used to go to the particular website , but it maintains the browser history and cookies, so we can use forward and backward button to navigate between the pages during the coding of Testcase
Training Summary
Selenium is a popular open-source web-based automation tool. This online course is a step by step guide to learn Selenium Concepts. It is recommended you refer the tutorials sequentially, one after the other.What should I know?
This free tutorial is designed for beginners with little or no automation experience. If you are new to testing first take the basic Software Testing class.
Want Selenium Lessons in your Inbox? Join our Email Course
Syllabus
First LookTutorial | What is Selenium? Introduction to Selenium Automation Testing |
Tutorial | What is Selenium WebDriver? Difference with RC |
It will be beneficial if you revisit Java, before reading tutorials on Webdriver
Tutorial | How to Download & Install Selenium WebDriver |
Tutorial | First Selenium Webdriver Script: JAVA Code Example |
Tutorial | Locators in Selenium IDE: CSS Selector, DOM, XPath, Link Text, ID |
Tutorial | Find Element and FindElements in Selenium WebDriver |
Tutorial | Selenium Form WebElement: TextBox, Submit Button, sendkeys(), click() |
Tutorial | How to Select CheckBox and Radio Button in Selenium WebDriver |
Tutorial | How to Click on Image in Selenium Webdriver |
Tutorial | How to Select Value from DropDown using Selenium Webdriver |
Tutorial | Locate Elements by Link Text & Partial Link Text in Selenium Webdriver |
Tutorial | Mouse Click & Keyboard Event: Action Class in Selenium Webdriver |
Tutorial | How to Upload & Download a File using Selenium Webdriver |
Tutorial | XPath in Selenium WebDriver: Complete Tutorial |
Tutorial | Alert & Popup Window Handling in Selenium WebDriver |
Tutorial | How to Handle Web Table in Selenium WebDriver |
Tutorial | Handling Dynamic Web Tables Using Selenium WebDriver |
Tutorial | Desired Capabilities in Selenium WebDriver |
Tutorial | How to Verify Tooltip using Selenium WebDriver |
Tutorial | How to Find All/Broken links using Selenium Webdriver |
Tutorial | Gecko (Marionette) Driver Selenium: Download, Install, Use with Firefox |
Tutorial | How to Download & Install TestNG in Eclipse for Selenium WebDriver |
Tutorial | TestNG Tutorial: Annotations, Framework, Examples in Selenium |
Tutorial | TestNG Groups: Include, Exclude with Example - Selenium Tutorial |
Tutorial | TestNG @Test Priority in Selenium |
Tutorial | Parallel Execution in Selenium: Session Handling & TestNG Dependency |
Tutorial | TestNG: How to Run Multiple Test Suites in Selenium |
Tutorial | TestNG Listeners in Selenium: ITestListener & ITestResult Example |
Tutorial | How to Execute Failed Test Cases in TestNG: Selenium WebDriver |
Tutorial | TestNG Report Generation in Selenium WebDriver |
Tutorial | Customize, PDF & Email TestNG Reports in Selenium WebDriver |
Tutorial | Page Object Model (POM) & Page Factory: Selenium WebDriver Tutorial |
Tutorial | Dataprovider & TestNG XML: Parameterization in Selenium(Example) |
Tutorial | Read & Write Data from Excel File in Selenium Webdriver: POI & JXL |
Tutorial | How to Select Date from DatePicker/Calendar in Selenium Webdriver |
Selenium Examples In Java
Tutorial | Selenium Grid Tutorial: Hub & Node (with Example) |
Tutorial | Maven & Jenkins Integration with Selenium: Complete Tutorial |
Tutorial | Selenium Automation Framework: Data Driven, Keyword Driven & Hybrid |
Tutorial | Database Testing using Selenium: Step by Step Guide |
Tutorial | Handling iFrames in Selenium Webdriver: switchTo() |
Tutorial | Cross Browser Testing using Selenium WebDriver |
Tutorial | How to Take Screenshot in Selenium WebDriver |
Tutorial | Log4j with Selenium Tutorial: Download, Install, Use & Example |
Tutorial | Selenium Headless Browser Testing: HTMLUnitDriver & PhantomJS |
Tutorial | Robot Class in Selenium Webdriver |
Tutorial | How to use AutoIT with Selenium Webdriver: File Upload Example |
Tutorial | How to Handle SSL Certificate in Selenium WebDriver |
Tutorial | How to Handle AJAX Call in Selenium Webdriver |
Tutorial | JavaScriptExecutor in Selenium WebDriver with Example |
Tutorial | Selenium Webdriver using Python: Tutorial with Example |
Tutorial | How to use IntelliJ IDEA & Selenium Webdriver |
Tutorial | Flash Testing with Selenium WebDriver |
Tutorial | Apache ANT with Selenium: Complete Tutorial |
Tutorial | How to Generate XSLT Report in Selenium Webdriver |
Tutorial | Github Integration with Selenium: Complete Tutorial |
Tutorial | Cookies Handling in Selenium WebDriver |
Tutorial | Using SoapUI with Selenium for Web Service Testing |
Tutorial | How to Create Firefox Profile in Selenium WebDriver |
Tutorial | Selenium with Cucumber (BDD Framework): Tutorial with Example |
Tutorial | How to Drag and Drop in Selenium WebDriver (EXAMPLE) |
Tutorial | Selenium C# Webdriver Tutorial: NUnit Example |
Tutorial | Creating Object Repository in Selenium WebDriver: XML & Properties file |
Tutorial | How to Scroll Down or UP a Page in Selenium Webdriver |
Tutorial | Sikuli Tutorial: How to use Sikuli with Selenium (EXAMPLE) |
Tutorial | XPath Contains, Sibling, Ancestor Functions in Selenium WebDriver |
Tutorial | Implicit, Explicit, & Fluent Wait in Selenium WebDriver |
Tutorial | Double click and Right Click in Selenium with Examples |
Tutorial | Selenium Proxy Authentication using Webdriver with EXAMPLE |
Tutorial | How to Download & Install Selenium IDE for Firefox |
Tutorial | Selenium IDE Tutorial for Beginners |
Tutorial | How to use Selenium IDE with Scripts & Commands (Assert, Verify) |
Tutorial | Verify Element Present, waitFor, andWait in Selenium IDE |
Tutorial | Store Variables, Echo, Alert, PopUp handling in Selenium IDE |
Tutorial | Selenium Core Extensions (User-Extensions.js) |
Tutorial | Breakpoint & Start Point in Selenium IDE |
Tutorial | Maximize Browser in Selenium |
Tutorial | Chrome Options & Desiredcapabilities: AdBlocker, Incognito, Headless |
Tutorial | Refresh Page using Selenium Webdriver |
Tutorial | Top 100 Selenium Interview Questions & Answers |
Tutorial | Selenium vs HP UFT (QTP): What's the Difference? |
Tutorial | Top 15 Selenium Alternatives |
Tutorial | Selenium Tutorial PDF |
Selenium Remote Webdriver Example Java
Live Selenium ProjectSelenium Java Code Examples
Join | Live Selenium Project: Banking Domain |
Join | Live Ecommerce Project: Selenium Automation |