If you are looking to start with web automation testing, Selenium is one of the best places to begin. This is not just my opinion, but last year over 39% of the market share was with Selenium, making it the go-to choice for beginner and seasoned developers.
I believe that learning Selenium not just helps you with web automation, but also helps you build a solid foundation for browser automation in general. Once you understand how Selenium interacts with web elements, handles browser actions, and executes tests, many of the same concepts carry over to other automation frameworks.
I have worked in Selenium across many projects over the years, and I’m putting together all the information one needs to make their first step in Selenium in 2026. We’ll go through the basic fundamentals, how to set up Selenium onto your device, common frameworks and much more.
What is Selenium?
Selenium is a widely-used open-source framework for automating web application testing. It allows developers and testers to interact with web browsers programmatically, simulating user actions like clicking buttons, filling forms, or navigating between pages.
Selenium supports multiple programming languages, including Python, Java, C#, Ruby, and JavaScript. One of Selenium’s key strengths is its ability to handle cross-browser and cross-platform testing, ensuring that web applications function consistently across different operating systems and devices.
Selenium works across multiple browsers and Selenium 4 also provides improved WebDriver functions and works well with testing tools like JUnit and TestNG for managing tests.
Why So Many Teams Choose Selenium
Selenium has been around for years, yet it continues to be one of the first choices for browser automation. Its popularity isn’t tied to a single feature. Whether you’re starting with automation or maintaining a large test suite, it fits naturally into existing development workflows and continues to scale as your testing needs grow.
- Runs across different browsers: The same test can be executed on browsers such as Chrome and Firefox, making it easier to verify consistent behaviour.
- Works on different operating systems: You don’t need separate automation suites for each operating system, which makes maintaining tests much simpler.
- Open source: Selenium is free to use, so teams can build and expand their automation without licensing costs.
- Fits your existing tech stack: It works with several popular programming languages, allowing teams to automate tests without changing how they already build software.
- Easy to add to release pipelines: Selenium integrates with modern CI/CD workflows, so automated tests can run whenever new code is pushed.
- Speeds up large test suites: With Selenium Grid, multiple tests can run at the same time instead of waiting for one another to finish.
- Grows with your project: As automation becomes more complex, Selenium can be combined with reporting tools and testing frameworks without requiring a complete rewrite.
- Well-established ecosystem: Years of community contributions, tutorials, and documentation make it easier to learn, troubleshoot, and extend Selenium.
The Three Main Parts of Selenium
I like to think of Selenium as a toolkit rather than a single tool. Each component has a different job, so you only use the ones that match what you’re trying to achieve.
- Selenium WebDriver (The Engine): Think of WebDriver as the engine of Selenium. It’s the part that actually controls the browser by clicking buttons, entering text, opening pages, and performing the same actions a real user would.
- Selenium IDE (The Wheels): Selenium IDE is the training wheels that lets you record browser interactions and play them back without writing code. This makes it a good starting point for learning browser automation or creating simple tests.
- Selenium Grid (The Factory): Once your test suite starts growing, running one test at a time becomes slow. Selenium Grid works like adding more machinery in a factory. Instead of waiting in a single queue, multiple tests run at the same time across different browsers and machines, reducing overall execution time.
For larger automation projects, cloud platforms such as BrowserStack Automate provide Selenium Grid without the need to manage your own infrastructure. You can execute tests in parallel across real browsers and devices, making it easier to scale your automation as your application grows.
Read More: How to Ensure Maximum Test Coverage
Setting up Selenium
Whether you’re using Python or Java, setting up Selenium is easy and allows you to automate web browsers effectively. This guide walks you through the steps for both languages, highlighting the latest tools and best practices.
Step 1: Install Prerequisites
1.1 Install Python or Java
For Python:
- Download and install Python from the official Python website.
- During installation, ensure you Add Python to PATH.
- It’s recommended to use a virtual environment to isolate dependencies:
- python -m venv venv
- source venv/bin/activate (On macOS/Linux)
- venv\Scripts\activate (On Windows)
For Java:
- Download and install the Java Development Kit (JDK) from Oracle or OpenJDK.
- Set up the JAVA_HOME environment variable and add it to the PATH.
1.2 Install WebDriver
For Chrome (using ChromeDriver):
- Download the ChromeDriver version that matches your installed version of Google Chrome.
- Either add ChromeDriver to your system’s PATH or reference it explicitly in your scripts.
For Firefox (using GeckoDriver):
- Download the latest GeckoDriver.
- Add it to your system’s PATH or reference it in your code.
Step 2: Set Up Your Project
2.1 For Python (Using PyCharm, VS Code, or other IDEs):
- Create a new project in PyCharm, VS Code, or any IDE of your choice.
- Install Selenium using pip:
pip install selenium
- Install WebDriver Manager for automated WebDriver management:
pip install webdriver-manager
2.2 For Java (Using Eclipse or IntelliJ IDEA):
- Create a new Java project in Eclipse or IntelliJ IDEA.
- Add Selenium via Maven or Gradle dependency:
- Maven (pom.xml):
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.10.0</version> <!-- Update to the latest --> </dependency>
- Gradle (build.gradle)
dependencies {
implementation 'org.seleniumhq.selenium:selenium-java:4.10.0' // Update to latest
}Step 3: Configure Selenium WebDriver
3.1 ChromeDriver Setup:
- For Python:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.example.com")
driver.quit()- For Java:
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class SeleniumTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", ChromeDriverManager.getInstance().getDriverPath());
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
driver.quit();
}
}3.2 Headless Browser Setup (Optional for CI/CD):
Headless mode allows Selenium to run without the browser window open, ideal for automation on CI servers.
- For Python:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
driver.get("https://www.example.com")
driver.quit()- For Java:
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.example.com");
driver.quit();Step 4: Write Your First Selenium Script
4.1 For Python (Basic Example):
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# Initialize the Chrome WebDriver
driver = webdriver.Chrome(ChromeDriverManager().install())
# Navigate to the desired webpage
driver.get("https://www.example.com")
# Find an element and interact with it
search_box = driver.find_element("name", "q") # Locate the element by its 'name' attribute
search_box.send_keys("Selenium") # Enter text into the search box
# Quit the browser
driver.quit()4.2 For Java (Basic Example):
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class FirstSeleniumScript {
public static void main(String[] args) {
// Setup WebDriverManager to manage ChromeDriver
WebDriverManager.chromedriver().setup();
// Initialize the Chrome WebDriver
WebDriver driver = new ChromeDriver();
try {
// Navigate to the desired webpage
driver.get("https://www.example.com");
// Find an element and interact with it
WebElement searchBox = driver.findElement(By.name("q")); // Locate element by 'name'
searchBox.sendKeys("Selenium"); // Enter text into the search box
} finally {
// Quit the browser to end the session
driver.quit();
}
}
}Step 5: Set Up Your IDE
5.1 For Python:
- PyCharm:
Download from here. Create a new project and install Selenium using pip in the terminal.
- VS Code:
Install the Python extension and use pip install selenium for dependency management.
5.2 For Java:
- Eclipse:
Download from here. Use Maven or Gradle for dependency management.
- IntelliJ IDEA:
Download from here. Similar to Eclipse, use Maven or Gradle to add dependencies.
With these steps, you should now be able to use Selenium for web automation with either Python or Java. Be sure to follow modern practices such as using WebDriver Manager and configuring headless mode for optimal performance in testing and CI/CD pipelines. Always stay updated with the latest versions of Selenium and WebDriver to ensure smooth automation.
Read More: How to set up Selenium on Visual Studio
What Are Locators in Selenium
Locators in Selenium are essential to identify elements on a web page for interacting with them (for example, clicking a button, entering text). Selenium provides multiple techniques for identifying elements on a web page:
- ID: The id attribute is often unique for elements, making it a reliable locator.
- Name: Elements with a name attribute can be located using this method.
- Class Name: Useful when elements share the same class name.
- Tag Name: Locates elements based on the HTML tag (for example, <input> or <button>).
XPath and CSS Selectors
XPath: A powerful and robust way to navigate and find elements in the HTML structure. It allows for complex queries and searching based on attributes, text content, or hierarchical structure.
Example:
driver.findElement(By.xpath(“//input[@name=’username’]”))
CSS Selectors: A quicker and more efficient alternative to XPath for locating elements using CSS classes, IDs, or attributes.
Example:
driver.findElement(By.cssSelector(“input[name=’username’]”))
Selenium Frameworks and Integrations
Selenium can be integrated with various frameworks and tools to enhance its testing capabilities. These integrations provide better management, reporting, and test execution.
1) Selenium Grid for Distributed Testing
- Selenium Grid enables running tests in parallel on different machines, browsers, and operating systems, allowing you to speed up your test execution and increase coverage.
- It’s often used in large-scale test environments where multiple test cases need to be run across various platforms simultaneously.
2) Integrating Selenium with TestNG or JUnit
TestNG and JUnit: Widely-used testing frameworks for Java that seamlessly integrate with Selenium for structured test execution and management.
- TestNG: Supports annotations like @Test, @Before, and @After for structuring test cases. It also supports parallel test execution, which works well with Selenium Grid.
- JUnit: Another popular framework for organizing tests in Java, with easy integration with Selenium to run automated tests.
3) CI/CD Integration with Jenkins
Jenkins is a widely used tool for automating the software delivery pipeline. It integrates seamlessly with Selenium to automate the execution of tests within a CI/CD pipeline.
Jenkins can be set up to trigger Selenium tests automatically whenever code is committed to the repository, ensuring continuous testing and faster feedback loops.
Read More: Keyword Driven Framework for Selenium
Common Challenges in Selenium Automation
Writing your first Selenium test may be easy, but keeping hundreds or thousands of tests reliable as the application evolves is where most teams spend their time. If these challenges aren’t addressed early, they can slow releases and increase the cost of maintaining automation:
- Frequent UI changes increase maintenance effort: When element locators change, existing tests can break even if the application’s functionality hasn’t changed. Teams end up spending valuable time fixing automation rather than on new features.
- Dynamic web applications create inconsistent test results: Modern applications load content asynchronously, making it difficult for tests to interact with elements at the right moment. This often leads to intermittent failures and repeated test executions.
- Cross-browser differences require additional validation: You can stumble across browser-specific and device-specific regressions, both needing their own additional tools to test further.
- Poor synchronization leads to flaky automation: Tests that don’t wait for the application to reach the expected state can fail unpredictably, reducing confidence in the entire automation suite.
- Growing test suites become harder to maintain: As new features are added, automation requires regular updates. Without a clear maintenance strategy, you will spend needless time on maintenance alone.
- Unexpected browser dialogs interrupt execution: Sudden alerts or pop-ups can stop automated tests unless they are predetermined on the test flow.
- Flaky tests slow down releases: When teams can’t trust test results, they spend more time rerunning failed tests and investigating false failures instead of shipping new features.
- Managing test data becomes increasingly complex: It gets increasingly hard for you to keep test environments consistent across multiple executions, especially when your tests depend on shared accounts or changing datasets.
Read More: Cypress vs Selenium: Key Differences
Writing Better Selenium Tests
Selenium is like a powerful toolbox. It works best when you know how to use it. By following the right practices, your automation tests will run smoothly and efficiently without unnecessary hiccups.
To help you keep your test suite running smoothly, here are the best practices that will make your automation more reliable.
- Use Explicit Waits: Instead of relying on hard-coded sleeps, use explicit waits to ensure elements are present before interacting with them.
- Create Reusable Methods: Develop functions for repetitive actions (such as clicking buttons or entering text) to minimize redundancy and improve test efficiency.
- Use Descriptive Locators: Choose locators that are unique and unlikely to change, such as ID or CSS selectors, to make your tests more stable.
- Separate Test Logic from Test Data: Keep test data separate from your scripts to make it easier to maintain and update.
- Parallel Test Execution: Run tests in parallel to save time, especially when dealing with large test suites.
- Use Page Object Model (POM): Structure your test scripts with the Page Object Model to enhance code clarity, maintainability, and reusability.
- Keep Tests Independent: Ensure each test is independent to avoid test dependencies and reduce failures due to order of execution.
- Regular Test Maintenance: Frequently update your test scripts to reflect any changes in the application and keep them efficient.
Building a Sample Selenium Test Case
This section demonstrates how to create a basic Selenium test case that automates the process of logging into a sample web application.
Writing a Test to Log in to a Sample Application
A simple login test case for a sample web application can be automated as follows. In this example, the test will:
- Open the login page.
- Enter the username and password.
- Submit the form.
- Verify if you successfully logged in.
Here’s the Selenium test case written in Python:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set up WebDriver (Ensure ChromeDriver is in PATH)
driver = webdriver.Chrome()
try:
# Open the login page of the sample application
driver.get("http://example.com/login")
# Wait for the username field to be visible
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "username")))
# Locate the username and password input fields
username_field = driver.find_element(By.ID, "username")
password_field = driver.find_element(By.ID, "password")
# Send input to the username and password fields
username_field.send_keys("myusername")
password_field.send_keys("mypassword")
# Submit the form by pressing Enter in the password field
password_field.send_keys(Keys.RETURN)
# Wait until the "Welcome" heading appears or another element confirming login
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//h1[text()='Welcome']")))
# Validate that the page contains the word "Welcome", indicating successful login
assert "Welcome" in driver.page_source
print("Login test passed.")
except AssertionError:
print("Login test failed: 'Welcome' not found.")
except Exception as e:
print(f"Test failed due to an error: {e}")
finally:
# Ensure the browser is closed after the test
driver.quit()Explanation of the Code:
- WebDriver Initialization: The Chrome WebDriver is initialized, and the browser is controlled during the test.
- Opening the Login Page: The driver.get() method opens the login page of the sample application.
- Locating Elements: By.ID locator strategy is used to find the username and password input fields.
- Sending Input: The send_keys() method inputs the username and password. The RETURN key is simulated to submit the login form.
- Waiting for the Login Confirmation: Use WebDriverWait to wait for the “Welcome” heading to appear on the page after login. This ensures that you don’t proceed with validation until the page has fully loaded.
- Validation: The test checks whether the word “Welcome” appears on the page using an assertion. If the text isn’t found, the test will fail.
- Error Handling: Exceptions are caught, and the failure reason is printed, ensuring you can identify issues easily.
Read More: How to write Selenium Test Cases
Locating Elements and Sending Input
In Selenium, elements can be located using different strategies such as by ID, name, XPath, CSS selector, and more. In the test case, By.ID is used to locate the username and password fields, which are assumed to have unique IDs in the HTML.
username_field = driver.find_element(By.ID, "username") password_field = driver.find_element(By.ID, "password")
You then send input to these fields using the send_keys() method:
username_field.send_keys("myusername")
password_field.send_keys("mypassword")This simulates typing the username and password into the fields.
Validating the Test Output
After performing actions (such as logging in), it’s important to validate that the test behaves as expected. In this case, you must check if the login was successful.
You can validate this by checking the page content for the word “Welcome”, which should appear after a successful login:
assert "Welcome" in driver.page_source
This assertion checks that “Welcome” is found in the page source, confirming that the login was successful. If the word “Welcome” is not found, the test will fail, providing feedback that something went wrong.
Alternatively, you could validate specific elements that appear only after a successful login, such as a user profile or a navigation menu.
How BrowserStack Supports Selenium Testing?
BrowserStack is a powerful cloud platform that enhances Selenium testing by allowing you to run tests on real devices and browsers. This helps ensure that your tests reflect the true user experience across various environments. Here’s how BrowserStack can benefit your Selenium testing:
- Running Tests on Real Devices and Browsers: BrowserStack Automate allows you to run Selenium tests on real devices and browsers, giving you a more accurate representation of how your application performs for end users.This feature eliminates the need for physical devices, providing access to a wide array of real browsers and devices for testing.
- Cross-Browser Testing: It allows you to test your app across multiple browsers and operating systems, making sure it works smoothly no matter what browser someone is using.
- Run Tests in Parallel: You can run multiple tests at the same time on different devices and browsers, which saves you a lot of time and speeds up the process.
- Instant Access to Environments: No more setting up virtual machines or devices. BrowserStack gives you instant access to the testing environments you need, so you can focus on running tests instead of managing infrastructure.
- Debugging Made Easy: If something goes wrong, BrowserStack provides video recordings, screenshots, and logs, so you can quickly figure out what went wrong and fix it.
- Works Well with CI/CD: BrowserStack integrates easily with continuous integration tools like Jenkins,CircleCI and GitHub Actions., allowing you to automate your testing as part of your regular development process.
Conclusion
Learning Selenium is about more than writing your first automation script. Once you understand how it interacts with a browser and how to structure reliable tests, you’ll have a foundation that applies to many web automation projects.
As your test suite grows, you’ll also start thinking beyond writing tests. Running them across different browsers, reducing maintenance, and fitting automation into your release process become just as important. That’s where combining Selenium with the right tools and workflows makes a real difference.
Whether you’re just getting started or expanding an existing automation framework, Selenium remains a practical choice for building browser tests that can grow with your application