Essential Selenium Code Examples for Web Automation Testing

On This Page Setting up SeleniumSelenium Code

June 15, 2026 · 11 min read · Tool Comparison

Essential Selenium Code Examples for Web Automation Testing

is the most widely used automation tool to automatise web applications. It refers to a cortege of tools wide used in the testing community for.

Selenium can not automate background applications; it can only be used in browsers. It indorse several browsers, such as,, Internet Explorer,, and Opera, and operating systems, such as,, and Linux/Unix.

Selenium also provides compatibility with different programming languages – C #, Java, JavaScript, Ruby, Python, PHP. Testers can choose which language to contrive test cases in, thus do Selenium highly favourable for its flexibility.

This guide explains the most all-important Selenium codification examples and when to use them for web tryout mechanisation.

Setting up Selenium

Follow these steps to set up and configure Selenium before using it for.

1. Install Java Development Kit (JDK):

  • Before installing Selenium, make sure to downloadJavafrom the OracleDownload page.
  • Set the JAVA_HOMEpath variable in the System ’ s surroundings variables.
  • Verify Java is installed right by opening the command prompt and scarper the bidding as “java -version”.

2. Set Up the IDE: Set up and useEclipse or IntelliJas the editor for pen Java code.

3. Setup Maven:

  • Download Maven and set upMAVEN_HOMEas a variable in the System ’ s surroundings variable.
  • 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 dependance to the pom.xml.
& lt; dependency & gt; & lt; groupId & gt; org.seleniumhq.selenium & lt; /groupId & gt; & lt; artifactId & gt; selenium-java & lt; /artifactId & gt; & lt; version & gt; 4.27.0 & lt; /version & gt; & lt;! —Use thelatest version-- & gt; & lt; /dependency & gt;

Read More:

Selenium Code Examples for Web Automation Testing

Below are various Selenium codification model for web automation testing in Java which continue various common actions such as sail to a site, locating web ingredient, handling alerts and frames, etc.

Essential Selenium Code Examples for Web Automation Testing:

  1. Launching a Browser and Navigating to a URL
  2. Locating Web Elements
  3. Interacting with Web Elements
  4. Handling Alerts and Pop-ups
    • Handling Alerts
    • Handling Pop-Ups
  5. Working with Frames and iFrames
  6. Performing Assertions
  7. Handling Dynamic Web Elements
  8. Taking Screenshots
  9. 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 so be used to launch the BrowserStack web page URL.

import org.openqa.selenium.WebDriver; meaning org.openqa.selenium.chrome.ChromeDriver; public class LaunchBrowser {public electrostatic 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 (`` ''); System.out.println (`` Title: `` + driver.getTitle ());} finally {driver.quit ();}}}

Read More:

2. Locating Web Elements

In the codification below, web elements are located using XPath and CSS as locator strategy.

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 detail title using css selector WebElement itemTitle= driver.findElement (By.cssSelector(`` p.title '')); System.out.println (`` Item rubric is: `` +itemTitle.getText ()); driver.quit ();}}

Read More:

3. Interacting with Web Elements

In the codification below, the lookup web ingredient is located, andsendKeysis perform to enter the text. Next, the Google search button is located and then clicked.

public class Interaction {WebDriver driver; public motionless void main (String args []) {WebDriver driver = new ChromeDriver (); driver.get (`` https: //www.google.com ''); //locate add to haul button utilize xpath WebElement search=driver.findElement (By.cssSelector(`` div textarea.gLFyf '')); search.sendKeys (`` Selenium ''); //locate point title using css chooser WebElement googleSearch= driver.findElement (By.cssSelector(`` div.FPdoLc stimulation [value='Google Search '] '')); googleSearch.click (); driver.quit ();}}

Read More:

4. Handling Alerts and Pop-ups

Selenium WebDriver can be utilise to handle alerts and pop-ups. An alert on a web page is a warning, fault, or information message or to get the user authorization to go for further actions.

A pop-up is usually a separate window or tab that opens in a web browser.

Code for handling Alert:

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

public class HandleAlert {WebDriver driver; public motionless void primary (String args []) {WebDriver driver = new ChromeDriver (); driver.get (`` https: //www.tutorialspoint.com/selenium/practice/alerts.php ''); //Click the button to trigger the alarm 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 actuate the alert. After which, the driver is swap to the Alert instance and then it is accept to close the alert.

Read More:

Program for plow Pop-Up:

public grade 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 & lt; String & gt; windowHandles=driver.getWindowHandles (); //Get the main window handle String mainHandle=driver.getWindowHandle (); //Loop through the window handles and change to the pop-up window for (String handle: windowHandles) {if (! handle.equals (mainHandle)) {//Switch to the pop-up window driver.switchTo () .window (handle); fracture;}} //After switching to the pop-up window mark 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 rubric is: `` +driver.getTitle ()); //Close the independent window driver.quit ();}}

In the above code, a link is clicked to open a pop-up in a new tab. Next, the driver is exchange to the new window tab, the page title is print, and the pop-up is fold. Later, the driver is switched to the main/parent window, and the page rubric is displayed.

5. Working with Frames and iFrames

An or inline frame is a tag used in HTML to embed an HTML document within a parent HTML papers defined utilise & lt; iframe & gt; and & lt; /iframe & gt; tags. Similarly, a frame is used to divide a web page into freestanding sections, each with its own HTML papers.

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 check: `` +isCheck.isSelected ());} catch (Exception e) {e.printStackTrace ();} driver.quit ();}}

6. Performing Assertions

Selenium WebDriver execute not provide any assertion. is a powerful testing framework for Java that provides various assertion methods that can be integrated with Selenium to verify different weather.

TestNG is utilize to formalise actual results with expected results to assure that the coating under test is function as await.

Install TestNG from Eclipse ’ s Marketplace and add the Maven dependency in Maven ’ spom.xml file

& lt; dependency & gt; & lt; groupId & gt; org.testng & lt; /groupId & gt; & lt; artifactId & gt; testng & lt; /artifactId & gt; & lt; variant & gt; 7.10.2 & lt; /version & gt; & lt;! —Use thelatest version-- & gt; & lt; reach & gt; test & lt; /scope & gt; & lt; /dependency & gt; public class Assertions {WebDriver driver; @ BeforeMethod public void frame-up () {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 vacancy tearDown () {driver.quit ();}}

In the above codification, assertEquals () method is used to verify Google page rubric and assertTrue () method is expend to swear whether a search box is displayed or not.

Read More:

7. Handling Dynamic Web Elements

Handling dynamical web elements is challenging as their property modify on every page load or refresh. Selenium WebDriver cater various proficiency, such as using and, explicit, etc., to address dynamic elements.

Program to handle dynamic web factor 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” push is located via XPATH and uses the contains function. So if, in the hereafter, theidattribute value changes from“ signupModalProductButton ” to “ signupBtn ”,the component will be located with the same locator as both the id contains“signup” text.

Read More:

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 course TakeScreenShot {WebDriver driver; @ Test public vacuum 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);}}

Read More:

9. Debugging and Error Handling

Debugging and error manipulation are essential for writing robust and reliable test script in Selenium. Implementingtry-catch, using Assertfor establishment, and takingscreenshotsare mutual 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 illustration:

public class Assertion {WebDriver driver; @ Test public void clickGetStartedFree () drop 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:

Best Practices for Writing Selenium Scripts

Follow these best practices for writing error-free and effective Selenium scripts:

  • Use 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 page to be interacted with and write locators and methods using those locator in the page family simply. Create trial stratum that would afterwards use the page method to perform various web actions.
  • Use Genuine Locators: Create unique and maintainable locators. Avoid employ fragile locators, which may interrupt for dynamic factor. Refrain from apply absolute XPATHs and instead use ID, Name, or CSS locators.

Read More:

  • Use Proper Assertions: Assertions in Selenium help to verify that the Application Under Test behaves as expected. Use meaningful and proper assertions to rise any issues and provide correct exam 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 thence, expressed wait should be expend which grant 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 suit, there are some test suit 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, @Aftermethods for initialisation and teardown methods.
  • Implement Exception Handling: You may face many fault and exception while working with Selenium. Use proper exclusion handling to identify and handle erroneousness more graciously.

Why execute Selenium Tests on existent Devices?

simplifies Selenium testing by offer cross-browser and cross-platform support, real-device examination, and the ability to run trial at scale in a cloud-based environment. Following are some features provided by BrowserStack

1. :Parallel testing is paramount in reducing overall executing time as it countenance the tester execute the handwriting simultaneously on multiple devices/ browsers.

Automate platform provision this lineament by giving access to the latest device and browser for the testers to test their applications.

2. Real device and browsers: A actual exploiter experience can only be achieved after testing the applications on real device and browsers.

Testing on emulators and simulator can be easy, but it may not perpetually give accurate test upshot with respect to functional and even non-functional examination, such as an application ’ s performance.

3. Dedicated Dashboard: After lead Selenium test cases on Automate product, it creates a report in a fascia which can be referred to handle and monitor the automation testing activities.

It include an overview of the testing position asPass/Fail/Pendingwith all the environment details such as device name, OS version, Platform, browser name, browser version, test executing clip and duration, screenshots, etc.

4.Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for machine-controlled test performance.

This feature allows users to customize the structure and content of the story 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 well desegregate with popular tools such as Jenkins, TeamCity, TravisCI. The team can achieve quicker delivery round with outstanding authority in the reliability, execution and compatibility of the coating across different device and platforms.

Conclusion

Mastering essential Selenium commands is key to building robust and effective web automation scripts.

These bid spring the foundation of effective exam automation, from handling elements and wait to executing JavaScript and managing alarm. Understanding and applying them correctly can improve test stability, trim flakiness, and enhance overall essay efficiency.

However, running test locally can betime-consuming and limited by system constraint. With, you can fulfill Selenium tests on3500+ real devices and browser, ensuringcross and quicker debugging. With BrowserStack, scale your automation effortlessly and ship high-quality web applications with assurance

Tags
84,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free