This guide provides a comprehensive overview of how to write effective Selenium tests in various languages and lists industry-standard best practices.
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.x.x</version> </dependency>
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class SeleniumTest { public static void main(String[] args) { ChromeOptions options = new ChromeOptions(); WebDriver driver = new ChromeDriver(options); try { driver.get("https://www.selenium.dev/"); System.out.println("Title: " + driver.getTitle()); } finally { driver.quit(); } } }
npm install selenium-webdriverconst {Builder} = require('selenium-webdriver'); (async function example() { let driver = await new Builder().forBrowser('chrome').build(); try { await driver.get('https://www.selenium.dev/'); console.log('Title:', await driver.getTitle()); } finally { await driver.quit(); } })();
pip install seleniumfrom selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() driver = webdriver.Chrome(options=options) try: driver.get("https://www.selenium.dev/") print("Title:", driver.title) finally: driver.quit()
dotnet add package Selenium.WebDriverusing OpenQA.Selenium; using OpenQA.Selenium.Chrome; using (IWebDriver driver = new ChromeDriver()) { driver.Navigate().GoToUrl("https://www.selenium.dev/"); Console.WriteLine("Title: " + driver.Title); }
gem install selenium-webdriverrequire 'selenium-webdriver' driver = Selenium::WebDriver.for :chrome begin driver.navigate.to "https://www.selenium.dev/" puts "Title: #{driver.title}" ensure driver.quit end
Static sleeps make tests slow and flaky. Instead, use Explicit Waits (WebDriverWait) to wait for specific conditions (e.g., element visibility, title contains). Language-specific sleep calls to avoid:
Thread.sleep()time.sleep()sleep()setTimeout() / await new Promise(r => setTimeout(r, ms))Thread.Sleep()Organize your tests by grouping elements and actions of each page into separate classes. This makes tests more readable and easier to maintain when the UI changes.
Each test should be able to run on its own, regardless of the order in which they are executed. Avoid relying on the side effects of previous tests. Use setup and teardown methods to manage state.
ID and Name when available.CSS Selectors for complex queries.XPath unless absolutely necessary (e.g., navigating to parent or sibling nodes) as it's generally slower and more fragile.Always call driver.quit() to ensure browser processes are cleaned up, even if a test fails. Use language-specific constructs like try-finally or using blocks.
You‘re already using it! Selenium Manager (this tool) automatically downloads and configures the correct drivers and browsers for you, so you don’t have to manage binaries manually.