Selenium is the most widely used automation tool to automate web applications. It refers to a suite of tools widely used in the testing community for cross browser testing.
Selenium cannot automate desktop applications; it can only be used in browsers. It supports several browsers, such as Chrome, Firefox, Internet Explorer, Safari, and Opera, and operating systems, such as Windows, Mac, and Linux/Unix.
Selenium also provides compatibility with different programming languages – C#, Java, JavaScript, Ruby, Python, PHP. Testers can choose which language to design test cases in, thus making Selenium highly favourable for its flexibility.
This guide explains the most essential Selenium code examples and when to use them for web test automation.
Setting up Selenium
Follow these steps to set up and configure Selenium before using it for website test automation.
1. Install Java Development Kit (JDK):
- Before installing Selenium, make sure to download Java from the Oracle Download page.
- Set the JAVA_HOME path variable in the System’s environment variables.
- Verify Java is installed correctly by opening the command prompt and running the command as “java -version”.
2. Set Up the IDE: Set up and use Eclipse or IntelliJ as the editor for writing Java code.
3. Setup Maven:
- Download Maven and set up MAVEN_HOME as a variable in the System’s environment variables.
- Verify Maven is installed correctly by opening the command prompt and running the command as “mvn – version”
4. Add Selenium Dependency:
- Create a Maven project in the IDE.
- Add the Selenium WebDriver dependency to the pom.xml.
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.27.0</version> <!—Use the latest version--> </dependency>
Selenium Code Examples for Web Automation Testing
Below are several Selenium code examples for web automation testing in Java which cover various common actions such as navigating to a website, locating web elements, handling alerts and frames, etc.
Essential Selenium Code Examples for Web Automation Testing:
- Launching a Browser and Navigating to a URL
- Locating Web Elements
- Interacting with Web Elements
- Handling Alerts and Pop-ups
- Handling Alerts
- Handling Pop-Ups
- Working with Frames and iFrames
- Performing Assertions
- Handling Dynamic Web Elements
- Taking Screenshots
- Debugging and Error Handling
- Try-Catch for Exception Handling
- Using Assertions for Validation
1. Launching a Browser and Navigating to a URL
The code below will create a Chrome driver instance and then be used to launch the BrowserStack web page URL.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class LaunchBrowser { public static void main(String[] args) { // Set the path to the ChromeDriver executable System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://www.browserstack.com"); System.out.println("Title: " + driver.getTitle()); } finally { driver.quit(); } } }
Read More: How to Launch Browser in Selenium
2. Locating Web Elements
In the code below, web elements are located using XPath and CSS as locator strategies.
public class LocatingElements { WebDriver driver; public static void main(String args[]) { WebDriver driver = new ChromeDriver(); driver.get("https://www.bstackdemo.com"); //locate add to cart button using xpath WebElement addToCart=driver.findElement(By.xpath("(//div[@class='shelf-item__buy-btn'])[1]")); addToCart.click(); //locate item title using css selector WebElement itemTitle= driver.findElement(By.cssSelector("p.title")); System.out.println("Item title is: "+itemTitle.getText()); driver.quit(); } }
Read More: Locators in Selenium
3. Interacting with Web Elements
In the code below, the search web element is located, and sendKeys is performed to enter the text. Next, the Google search button is located and then clicked.
public class Interaction { WebDriver driver; public static void main(String args[]) { WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); //locate add to cart button using xpath WebElement search=driver.findElement(By.cssSelector("div textarea.gLFyf")); search.sendKeys("Selenium"); //locate item title using css selector WebElement googleSearch= driver.findElement(By.cssSelector("div.FPdoLc input[value='Google Search']")); googleSearch.click(); driver.quit(); } }
Read More: Selenium WebElement Commands
4. Handling Alerts and Pop-ups
Selenium WebDriver can be used to handle alerts and pop-ups. An alert on a web page is a warning, error, or information message or to get the user authorization to proceed for further actions.
A pop-up is usually a separate window or tab that opens in a web browser.
Code for handling Alert:
public class HandleAlert { WebDriver driver; public static void main(String args[]) { WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/selenium/practice/alerts.php"); //Click the button to trigger the alert box WebElement alertBtn=driver.findElement(By.xpath("//label[text()='Click Button to see alert']//following-sibling::button")); alertBtn.click(); //Switch to the alert and accept it Alert alert=driver.switchTo().alert(); alert.accept(); } }
In the above code, a button is clicked to trigger the alert. After which, the driver is switched to the Alert instance and then it is accepted to close the alert.
Read More: How to handle Alerts and Popups in Selenium?
Program for handling Pop-Up:
public class PopUpWindows { WebDriver driver; public static void main(String args[]) { WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3)); driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login"); //Click the link to trigger the pop up window WebElement popUp=driver.findElement(By.cssSelector("p.oxd-text a")); popUp.click(); //Get all window handles Set<String> windowHandles=driver.getWindowHandles(); //Get the main window handle String mainHandle=driver.getWindowHandle(); //Loop through the window handles and switch to the pop-up window for(String handle: windowHandles) { if(!handle.equals(mainHandle)) { //Switch to the pop-up window driver.switchTo().window(handle); break; } } //After switching to the pop-up window print the page title System.out.println("Pop Up window title is: "+driver.getTitle()); //Close the pop-up window driver.close(); //Switch to the main window driver.switchTo().window(mainHandle); //After switching to the main window print the page title System.out.println("Main window title is: "+driver.getTitle()); //Close the main window driver.quit(); } }
In the above code, a link is clicked to open a pop-up in a new tab. Next, the driver is switched to the new window tab, the page title is printed, and the pop-up is closed. Later, the driver is switched to the main/parent window, and the page title is displayed.
5. Working with Frames and iFrames
An iFrame or inline frame is a tag used in HTML to embed an HTML document within a parent HTML document defined using <iframe> and </iframe> tags. Similarly, a frame is used to divide a web page into separate sections, each with its own HTML document.
public class Iframes { WebDriver driver; public static void main(String args[]) { WebDriver driver = new ChromeDriver(); driver.get("https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_display_checkbox_text"); driver.switchTo().frame(1); try { WebElement isCheck=driver.findElement(By.cssSelector("input#myCheck")); System.out.println("Check box is checked: " +isCheck.isSelected()); }catch (Exception e) { e.printStackTrace(); } driver.quit(); } }
6. Performing Assertions
Selenium WebDriver does not provide any assertions. TestNG is a powerful testing framework for Java that provides various assertion methods that can be integrated with Selenium to verify different conditions.
TestNG is used to validate actual results with expected results to ensure that the application under test is functioning as expected.
Install TestNG from Eclipse’s Marketplace and add the Maven dependency in Maven’s pom.xml file
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.10.2</version> <!—Use the latest version--> <scope>test</scope> </dependency> public class Assertions { WebDriver driver; @BeforeMethod public void setUp() { driver = new ChromeDriver(); driver.get("https://www.google.com"); } @Test public void verifyPageTitle() { Assert.assertEquals(driver.getTitle(), "Google"); WebElement search=driver.findElement(By.cssSelector("div textarea.gLFyf")); Assert.assertTrue(search.isDisplayed()); } @AfterMethod public void tearDown() { driver.quit(); } }
In the above code, assertEquals() method is used to assert Google page title and assertTrue() method is used to assert whether a search box is displayed or not.
Read More: Assert and Verify Methods in Selenium
7. Handling Dynamic Web Elements
Handling dynamic web elements is challenging as their attributes change on every page load or refresh. Selenium WebDriver provides various techniques, such as using XPATH and CSS Selectors, explicit waits, etc., to handle dynamic elements.
Program to handle dynamic web elements using XPATH with contains function:
public class HandleDynamicElements { WebDriver driver; @Test public void clickGetStartedFree() { driver = new ChromeDriver(); driver.get("https://www.browserstack.com"); WebElement getStartedFree= driver.findElement(By.xpath("//a[contains(@id,'signup')]")); getStartedFree.click(); driver.quit(); } }
In the above code, “Get Started Free” button is located via XPATH and uses the contains function. So if, in the future, the id attribute value changes from “signupModalProductButton” to “signupBtn”, the element will be located with the same locator as both the id contains “signup” text.
Read More: findElement and findElements in Selenium
8. Taking Screenshots
To take a web screenshot using Selenium WebDriver, you need to use the TakeScreenshot interface. This interface allows you to capture a screenshot of the current browser window and save it into a file.
public class TakeScreenShot { WebDriver driver; @Test public void clickProducts() throws IOException { driver = new ChromeDriver(); driver.get("https://www.browserstack.com"); WebElement products= driver.findElement(By.cssSelector("button#products-dd-toggle")); products.click(); takeScreenShot(driver, "screenshot.png"); driver.quit(); } public void takeScreenShot(WebDriver driver, String fileName) throws IOException { File screenshot =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); File dest= new File(fileName); FileUtils.copyFile(screenshot, dest); } }
9. Debugging and Error Handling
Debugging and error handling are crucial for writing robust and reliable test scripts in Selenium. Implementing try-catch, using Assert for validations, and taking screenshots are common ways to handle this.
Try-Catch example:
public class TryCatchImp { WebDriver driver; @Test public void clickGetStartedFree() throws IOException { driver = new ChromeDriver(); driver.get("https://www.browserstack.com"); try { WebElement getStartedFree= driver.findElement(By.cssSelector("a#signupModalProductButton")); getStartedFree.click(); }catch (NoSuchElementException e) { System.out.println("Element could not be clicked: "+e.getStackTrace()); } driver.quit(); } }
Assertion example:
public class Assertion { WebDriver driver; @Test public void clickGetStartedFree() throws IOException { driver = new ChromeDriver(); driver.get("https://www.browserstack.com"); try { WebElement getStartedFree= driver.findElement(By.cssSelector("a#signupModalProductButton")); getStartedFree.click(); Assert.assertTrue(driver.getCurrentUrl().contains("sign_up")); }catch (Exception e) { System.out.println("Assert failed: "+e.getStackTrace()); } driver.quit(); } }
Read More: How to start with Selenium Debugging
Best Practices for Writing Selenium Scripts
Follow these best practices for writing error-free and efficient Selenium scripts:
- Use Page Object Model (POM) as design pattern: The POM helps to separate the page specific logic and the test specific login in two different places and makes the code more maintainable and reusable.
Create different page classes for pages to be interacted with and write locators and methods using those locators in the page class only. Create test classes that would later use the page methods to perform various web actions. - Use Genuine Locators: Create unique and maintainable locators. Avoid using fragile locators, which may break for dynamic elements. Refrain from using absolute XPATHs and instead use ID, Name, or CSS locators.
Read More: Best Practices for Selenium Test Automation
- Use Proper Assertions: Assertions in Selenium help to verify that the Application Under Test behaves as expected. Use meaningful and proper assertions to surface any issues and provide correct test results.
- Use Explicit Wait Instead of Implicit Wait: Implicit waits are the waits which are applied globally to all the elements on the web page. Using implicit waits may lead to unpredictable results and therefore, explicit wait should be used which allows you to wait for the specific conditions before proceeding for any action to avoid any exception.
- Write Independent and Separate Test Cases: While working with a huge set of test cases, there are some test cases that depend on the state of other test cases to execute. In automation scripts, each test case should be run independently without depending on the success of any other test case. Use TestNG @Before, @After methods for initialisation and teardown methods.
- Implement Exception Handling: You may face many errors and exceptions while working with Selenium. Use proper exception handling to identify and handle errors more gracefully.
Why execute Selenium Tests on real Devices?
BrowserStack Automate simplifies Selenium testing by offering cross-browser and cross-platform support, real-device testing, and the ability to run tests at scale in a cloud-based environment. Following are some features provided by BrowserStack
1. Parallel Testing: Parallel testing is paramount in reducing overall execution time as it lets the testers execute the scripts simultaneously on multiple devices/ browsers.
Automate platform provision this feature by giving access to the latest devices and browsers for the testers to test their applications.
2. Real devices and browsers: A genuine user experience can only be achieved after testing the applications on real devices and browsers.
Testing on emulators and simulators can be easy, but it may not always give accurate test results with respect to functional and even non-functional testing, such as an application’s performance.
3. Dedicated Dashboard: After running Selenium test cases on Automate product, it creates a report in a dashboard which can be referred to manage and monitor the automation testing activities.
It includes an overview of the testing status as Pass/Fail/Pending with all the environment details such as device name, OS version, Platform, browser name, browser version, test execution time and duration, screenshots, etc.
4.Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for automated test execution.
This feature allows users to customize the structure and content of the report according to their needs. It can include a wide range of test data, such as test execution status, device and browser configurations, test duration, video recording, screenshots, etc.
5. Easy Integration with CI/CD Pipeline: Automate can be easily integrated with popular CI/CD tools such as Jenkins, TeamCity, TravisCI. The team can achieve faster delivery cycles with great confidence in the reliability, performance and compatibility of the application across different devices and platforms.
Conclusion
Mastering essential Selenium commands is key to building robust and efficient web automation scripts.
These commands form the foundation of effective test automation, from handling elements and waits to executing JavaScript and managing alerts. Understanding and applying them correctly can improve test stability, reduce flakiness, and enhance overall testing efficiency.
However, running tests locally can be time-consuming and limited by system constraints. With BrowserStack Automate, you can execute Selenium tests on 3500+ real devices and browsers, ensuring cross browser compatibility and faster debugging. With BrowserStack, scale your automation effortlessly and ship high-quality web applications with confidence