Efficient Selenium ChromeDriver Testing: A Complete Guide
Urwashi Priya
Posted On: September 13, 2023
211856 Views
17 Min Read
Running Selenium tests on Chrome using Selenium ChromeDriver enables automated testing of web applications. ChromeDriver is a web driver designed explicitly for Chrome browsers, facilitating interaction between Selenium scripts and Chrome’s browser functionality, allowing seamless testing and validation of web application behavior.
Fascinatingly, There are two ways we can execute our tests. One involves the usual manual configuration approach, while the other uses the latest “Selenium Manager,” which comes out of the box with Selenium bindings. We’ll explore both methods and their code implementations in this blog.
TABLE OF CONTENTS
- What is Selenium ChromeDriver?
- Why is ChromeDriver important for Selenium?
- Manual Way to Install and Setup Selenium ChromeDriver for Testing
- Steps to Run Automation Test With Selenium ChromeDriver
- Automating the Manual Process Of Managing Drivers
- Steps to Run Automation Test On LambdaTest Cloud Grid
- Advanced Techniques for chromedriver selenium
- Frequently Asked Questions
What is Selenium ChromeDriver?
Selenium is a powerful framework used for automating web browsers. It allows developers and testers to simulate user interactions with web applications by writing scripts in various programming languages. These scripts can perform multiple tasks, including clicking buttons, filling out forms, and navigating different web pages.
When using Selenium with the Google Chrome browser, ChromeDriver comes into the picture. It acts as a bridge between Selenium and Chrome. It helps in enabling communication and interaction between the two. In simpler terms, ChromeDriver is like a translator that allows Selenium to understand and control the Chrome browser effectively.
When using Selenium with the Google Chrome browser, ChromeDriver comes into the picture. It acts as a bridge between Selenium and Chrome. It helps in enabling communication and interaction between the two. In simpler terms, ChromeDriver is like a translator that allows Selenium to understand and control the Chrome browser effectively.
It works by connecting with the Chrome browser through a WebDriver interface. It sends commands from Selenium to Chrome, like opening a URL, finding elements on a web page, or executing JavaScript code. It also retrieves information from the browser, such as page titles, URLs, or element attributes.
Why is ChromeDriver important for Selenium?
Just like a translator helps two people communicate effectively, ChromeDriver ensures that Selenium can understand and control Chrome. It serves as the intermediary, enabling Selenium to speak the same language as Chrome. It provides a set of instructions and commands that Selenium can use to control the browser effectively.
Automate your tests on a Selenium cloud grid of 3000+ real browsers. Try LambdaTest Today!
Installing and Setting Up Selenium ChromeDriver Manually
Using Selenium ChromeDriver generally comprises 3 steps.
- Download and Install the appropriate Selenium ChromeDriver
- Setup
- Maintain
Utilizing Selenium Manager streamlines the typical 3-step process associated with ChromeDriver usage. Instead of manually downloading, installing the suitable Selenium ChromeDriver, and configuring it, you can now rely on Selenium Manager to handle these tasks seamlessly. This approach eliminates manual intervention and management, offering a more streamlined and efficient way to incorporate ChromeDriver into your automation workflow.
First, we will see the traditional method.
Installing Selenium ChromeDriver on Windows
Here’s a step-by-step guide to installing Selenium ChromeDriver on Windows.
If you are installing ChromeDriver of version less than or equal to 114.0 follow these steps:
- Download the required version of ChromeDriver for Windows.
- Extract the contents of the downloaded ZIP file to a location of your choice on your computer.
- Open File Explorer and navigate to the extracted ChromeDriver folder.
- Copy the path of the ChromeDriver executable file (ChromeDriver.exe).
- Open about section in the settings
- In the System Properties window, click on “Advanced system settings“. A pop-up window appears.
- Click on the “Environment Variables” button.
- Under the “System variables” section, locate the “Path” variable and select “Edit.”
- Click on “New” and paste the copied path of the ChromeDriver executable.
- Click “OK” to save the changes, and ChromeDriver is now installed on your Windows system.
Note: Ensure that ChromeDriver and your browser’s version should be the same.
Now, the question arises, how do you check your browser version?
Click on the three dots in the top right corner of the Chrome browser. Go to option “Settings” and click on the “About Chrome” option.
To install ChromeDriver of version 115.0 onwards, we need to follow these steps:
After ChromeDriver 114.0, the steps of installing got changed. Now, Google has launched CFTA dashboard.
A version of Chrome will be installed, used explicitly for automation testing.
- Click on Stable and we will see a dashboard as shown below.
- Copy the URL according to your system specification, and the required version of Chrome and ChromeDriver gets installed.
This version of Chrome is used only for automation purposes and opens with this notification at the top.
Note: Only Selenium version 4.11.0 and above is compatible with Chrome browser version 115.0 and above.
All the other steps remain the same.
Installing Selenium ChromeDriver on Mac
Once the download is complete, open the downloaded ZIP file. In the Finder, press Command+Shift+G and enter “/usr/local/bin” to go to the bin directory. Copy the extracted ChromeDriver executable file (ChromeDriver) into the “/usr/local/bin” directory.
Installing Selenium ChromeDriver on Linux
Extract the contents of the downloaded ChromeDriver ZIP file. You can use the ‘unzip‘ command followed by the name of the ZIP file. For example: unzip ChromeDriver_linux64.zip.
Decide on a location where you want to store the ChromeDriver executable. It’s common to store it in the ‘/usr/local/bin’ directory, which is already in the system’s PATH. To move the ChromeDriver executable to ‘/usr/local/bin’, use the following command: sudo mv ChromeDriver /usr/local/bin.
Once the ChromeDriver executable is moved, you need to make it executable. Run the following command to grant executable permissions: sudo chmod +x /usr/local/bin/ChromeDriver.
How to check and update the installed version of Selenium ChromeDriver
To check the installed version of Selenium ChromeDriver, one can follow these steps:
- Open a terminal or command prompt.
- Type the following command:
- The terminal will display the version number of the installed Selenium ChromeDriver.
1 |
chromeDriver --version or chromeDriver -v |
Alternatively, one can also run the command chromeDriver
without any additional arguments. This will start ChromeDriver, and the output will display the version information.
This command only works when that chromedriver is installed explicitly in the environment variables path. If we use Selenium Manager, then it will be of NO use. For that, one has to use this code as an alternative.
1 2 3 4 5 6 7 8 9 |
from selenium import webdriver # Selenium Manager driver = webdriver.Chrome() str1 = driver.capabilities["browserVersion"] str2 = driver.capabilities["chrome"]["chromedriverVersion"].split(" ")[0] print("browserVersion: ", str1) print("chromedriverVersion: ", str2) driver.quit() # Use driver.quit() to properly close the browser |
To update the installed version of Selenium ChromeDriver, one can follow these steps:
- Check for the current version of ChromeDriver.
- Go to Selenium’s official page to download the latest version of Selenium ChromeDriver and replace the existing one on your local machine. For downloading the new version, you can refer here .
Indeed, while working with specific ChromeDriver versions for compatibility, you might encounter challenges during the maintenance phase. Updates to browsers and WebDriver versions can lead to mismatches that result in test failures. When a new version enhances features or fixes issues, your existing test scripts might not function as expected due to these version discrepancies. Manual intervention can be automated to make the lives of the testers or developers easy, which will be discussed further in this blog.
Steps to Run Automation Test With Selenium ChromeDriver
This section will show how to run the test scripts on one’s system.
Prerequisites
The following prerequisites must be fulfilled.
- Ensure you have Python or Java installed on your computer.
- Ensure you have Selenium and Selenium ChromeDriver installed.
- Create your Project Files: Create a new directory to store your Selenium project. Inside the project directory, create a Python or Java file as per your choice where you’ll start with your Selenium code (e.g., my_selenium_test.py or MySeleniumTest.java).
Writing a simple test script in Python
Let’s look at an example of how you can write a simple test script using Selenium.
Here we have written a simple Python script, which will open an “e-commerce playground”. This is a demo website maintained by LambdaTest to run tests and learn the concepts. This script will print the title of the website. In our example, it will print “Your Store”. Lastly, our script will hover over an element using the class name.
In Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.service import Service as ChromeService import time import os # Set the specific path to the Chromedriver executable chromedriver_path = "C:/Users/prati/Downloads/chromedriver_win32/chromedriver.exe" # If the user has set the path in the environment variable, we can call in this way chromedriver_path = os.environ.get("Chromedriver_Path") # Also note, we need to declare chromedriver_path either by mentioning the specific path or by setting the path in the environment variable. # Create Chrome driver options = webdriver.ChromeOptions() service = ChromeService(executable_path=chromedriver_path) driver = webdriver.Chrome(service=service, options=options) # Open the website driver.get("https://ecommerce-playground.lambdatest.io/") #print the name of the title title = driver.title print(title) #hovering over an element a = ActionChains(driver) element= driver.find_element(By.CLASS_NAME, "lazy-load") a.move_to_element(element).perform() time.sleep(10) driver.close() |
Output:
Automating the Manual Process Of Managing Drivers
The pain of following the manual procedure can be effectively addressed by leveraging a third-party library like WebDriverManager. Selenium has used this concept to ship “Selenium Manager” out of the box as soon as you install the Selenium bindings. With Selenium Manager, you no longer have to worry about finding the right version, downloading it, setting up and maintaining it in the system path as it automates the steps involved.
We just need to write the following piece of code,
driver = webdriver.Chrome()
A Chrome’s driver object is instantiated, but this time, without having to download the driver binaries and mentioning a path as we saw in the manual procedure. This line of code works in a way such that it first identifies the current version of the browser, looks for a compatible driver in the environment, if found, uses it to instantiate the chrome driver object, otherwise, it downloads as per the version of chrome being used and manages it.
1 2 3 4 5 |
from selenium import webdriver driver = webdriver.Chrome() driver.get("https://ecommerce-playground.lambdatest.io/") driver.quit() |
Automate your tests on a Selenium cloud grid of 3000+ real browsers. Try LambdaTest Today!
Steps to Run Automation Test On LambdaTest Cloud Grid
To run your automation test on LambdaTest Cloud Grid, follow these steps:
- Sign up for a LambdaTest account: Go to the LambdaTest website and sign up for an account if you still need to.
- Retrieve your LambdaTest credentials: You can find these credentials in the “Automation” section of your LambdaTest account dashboard.
- Update your test code to integrate with LambdaTest:
- Import Statements:
- Fixture Definition (driver):
- Test Scenario (test_scenario):
- Opening a specific website using driver.get().
- Getting the title of the webpage and asserting that it’s equal to “Your Store“.
- Scrolling down the page using JavaScript (driver.execute_script()).
- Performing a hover action over an element on the page using ActionChains.
- Adding some wait time using time.sleep() to simulate interactions and visual checks.
- The test is followed by a comment suggesting that more assertions or steps can be added based on the test scenario.
- Main Execution:
- Run the test with LambdaTest integration: Execute the following command in the terminal to run your test code with the LambdaTest integration:
- Review test results: Once the test run is complete, you can review the test results and logs on the LambdaTest dashboard. You’ll be able to see the screenshots, video recordings, and other details related to the test execution.
Note: access key information is present on the right hand side.
To generate capabilities, go to capability generator. Select the code for which you want to generate and paste it. Here’s an example of how you can modify your code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import pytest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options as ChromeOptions import time @pytest.fixture def driver(request): # Set the desired capabilities for LambdaTest Cloud Grid lt_options = { "build": "First build", "name": "First Test", "platformName": "Windows 10", "video": True, "w3c": True, # informing latest Selenium 4 being used "browserName": "Chrome", "browserVersion": "114.0", "selenium_version": "4.9.0", } # Replace "YOUR_LAMBDATEST_USERNAME" and "YOUR_LAMBDATEST_ACCESS_KEY" with your actual LambdaTest credentials username = "" access_key = "xx" remote_url = "http://{}:{}@hub.lambdatest.com/wd/hub".format(username, access_key) browser_options = ChromeOptions() # adding the capability to the chrome browser_options.set_capability("LT:Options", lt_options) # Create the WebDriver instance with the desired capabilities driver = webdriver.Remote(command_executor=remote_url, options=browser_options) yield driver # Quit the WebDriver instance after the test completes driver.quit() def test_scenario(driver): # Open the website driver.get("https://ecommerce-playground.lambdatest.io/") # Get the title of the page title = driver.title assert title == "Your Store" # Scrolling the entire webpage driver.execute_script("window.scrollTo(0, document.body.scrollHeight)") time.sleep(10) # Hovering over an element actions = ActionChains(driver) element = driver.find_element(By.CLASS_NAME, "lazy-load") actions.move_to_element(element).perform() time.sleep(10) # Add assertions or additional steps as per your test scenario if __name__ == '__main__': pytest.main() |
Make sure to replace the placeholders (Your Build Name
, Your LambdaTest Username
, Your LambdaTest Access Key
) with the appropriate values from your LambdaTest account.
This code is a Python script using the pytest
testing framework and the Selenium
framework to automate browser testing on the LambdaTest cloud platform. The purpose of this script is to demonstrate how to set up and perform automated tests on a website using the Selenium WebDriver and interact with the LambdaTest Cloud Grid for testing on different browsers and platforms.
Here’s a step-by-step explanation of the code:
The code starts with importing necessary libraries: pytest for testing and modules from Selenium for browser automation.
The @pytest.fixture decorator defines a fixture named driver. A fixture is a way to set up and tear down resources needed for testing.
Inside the fixture, the desired capabilities for the LambdaTest Cloud Grid are defined using the lt_options dictionary. These capabilities specify the browser, version, platform, test name, build information, and other options for the test.
Finally, a WebDriver instance is created using the webdriver.Remote class. The instance connects to the LambdaTest hub using the constructed remote URL and Chrome options.
Fixture Teardown:
A yield statement is used, which means that the code after yield will run after the test is done executing.
In this case, the WebDriver instance is closed using driver.quit().
The actual test is defined as a function called test_scenario that takes the driver fixture as an argument.
The test involves the following steps:
The script’s main block is wrapped in an if __name__ == ‘__main__’: condition to ensure that its code is only executed when the script is run directly (not when imported as a module).
It invokes the pytest.main() function to run the test.
1 |
pytest name_of_your_test.py |
That’s it! Your automation test will now run on the LambdaTest Cloud Grid using the desired capabilities you specified.
Advanced Techniques for Selenium ChromeDriver
Selenium ChromeDriver provides various advanced features which can enhance browser automation capabilities, thus making tests more efficient and effective.
Working with popups and alerts with ChromeDriver
Let’s look at how to handle popups with Selenium ChromeDriver:
Handle popups or new windows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("https://www.lambdatest.com/selenium-playground/window-popup-modal-demo") current_window = driver.current_window_handle print(current_window) # Opening a popup or new window popup_element = driver.find_element(By.XPATH, '//*[@id="__next"]/section[3]/div/div/div[1]/div/div[3]/a') popup_element.click() # Fetching the handles of all open windows window_handles = driver.window_handles # Switch to the new window or popup for handle in window_handles: if handle != driver.current_window_handle: driver.switch_to.window(handle) break # Close the popup or new window driver.close() |
Handle alerts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
from selenium import webdriver from selenium.webdriver.common.by import By import time # Create a Chrome driver instance driver = webdriver.Chrome() # Navigate to a page that triggers an alert driver.get("https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo") time.sleep(5) # Trigger the alert (e.g., by clicking a button) driver.find_element(By.XPATH, '//*[@id="__next"]/section[3]/div/div/div/div[1]/p/button').click() time.sleep(5) # Switch to the alert alert = driver.switch_to.alert time.sleep(5) # Accept the alert (click OK) alert.accept() time.sleep(5) # Quit the browser driver.quit() |
Running headless Chrome with ChromeDriver
To run headless Chrome with ChromeDriver, you can configure the ChromeOptions object to enable the headless mode.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from selenium import webdriver from selenium.webdriver.chrome.options import Options as ChromeOptions # Create ChromeOptions and set headless mode options = ChromeOptions() options.add_argument("--headless=new") # Enable headless mode # Create Chrome driver driver = webdriver.Chrome() # Use the driver as usual driver.get("https://ecommerce-playground.lambdatest.io/") # Perform other actions and assertions # Close the browser driver.quit() |
In this example, we create a ChromeOptions
object and add the --headless
argument using the add_argument
method. This enables the headless mode for Chrome, meaning the browser runs without a visible GUI.
We then create the Chrome driver by passing the ChromeService
and ChromeOptions
objects. The headless mode will be applied to the driver, and you can use it, as usual, to perform actions and assertions on web pages.
By configuring the ChromeOptions
object with the --headless
argument, you can run ChromeDriver in headless mode, which is helpful for scenarios where you don’t require a visible browser window during the automation process.
Tips for optimizing the ChromeDriver for faster and more reliable testing
To optimize the ChromeDriver for faster and more reliable testing, here are some tips you can follow:
- Use the Latest Browser:
- Configure Chrome Options Appropriately:
- Use headless mode (
--headless
) to run tests without opening a visible browser window. This can significantly improve performance. - Set the window size to a reasonable value (
--window-size=1920x1080
) to match common screen resolutions and avoid unnecessary rendering overhead. - Disable extensions (
--disable-extensions
) to eliminate potential conflicts or slowdowns caused by installed extensions during testing. - Use Implicit Waits:
- Utilize Explicit Waits:
- Optimize Locator Strategies:
- Use Page Object Model (POM) or Component-Based Design:
- Minimize Network and Resource Usage:
- Parallelize Test Execution:
Newer versions often include bug fixes, performance improvements, and compatibility updates. Check the ChromeDriver download page for the latest releases and update your ChromeDriver accordingly.
Optimize your Chrome options based on your testing requirements. For example:
Set an implicit wait time to allow the ChromeDriver to wait for elements to become available before throwing an exception. Implicit waits can help stabilize and synchronize your tests, especially when dealing with dynamic web content or network latency.
1 2 |
# Wait up to 10 seconds for elements to be found driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); |
In addition to implicit waits, use explicit waits to wait for specific conditions to be met before proceeding with your test. Explicit waits allow you to wait for elements to be clickable, visible, or contain specific text. This helps ensure that the elements are fully loaded and ready for interaction.
1 2 3 |
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".classlocator"))); |
Choose efficient locator strategies (such as ID, Class, CSS selectors, or XPath) to locate elements on the page. These strategies should be unique, stable, and fast. Avoid using slow or brittle locators that rely on element position or visible text.
Adopt a structured approach like the Page Object Model or component-based design to organize your code. This helps improve test maintainability, reusability, and readability. By separating the page interactions into separate classes or components, your tests become more modular and easier to maintain.
Optimize your tests to minimize unnecessary network requests and resource usage. Avoid excessive page refreshes, unnecessary navigation, or redundant interactions. Leverage caching mechanisms and reuse existing browser sessions whenever possible to reduce test execution time.
If your testing framework allows, consider running tests in parallel to take advantage of available system resources. This can significantly speed up test execution, especially when running a large test suite. However, ensure that your system can handle the concurrent execution of tests without resource contention or instability.
Conclusion
In conclusion, Selenium ChromeDriver is a vital tool for automating web browser interactions, enabling precise testing and validation of web applications. The introduction of Selenium Manager streamlines the manual process of ChromeDriver management, making setup and maintenance more efficient.
Through Selenium Manager, ChromeDriver version compatibility challenges are alleviated, allowing for seamless automation. Leveraging advanced techniques like handling popups, alerts and running headless Chrome further enhances testing capabilities.
Optimizing ChromeDriver performance with the latest browser versions, efficient configurations, and smart wait strategies ensures faster and more reliable testing. Integration with the LambdaTest Cloud Grid expands testing coverage across diverse browsers and platforms.
As the realm of automation evolves, a solid grasp of Selenium ChromeDriver and its efficient management is crucial for delivering high-quality web applications.
Frequently Asked Questions (FAQs)
How do I troubleshoot installation issues with Selenium ChromeDriver?
If you encounter issues during installation, ensure that you have the correct version of ChromeDriver for your Chrome browser version. Also, make sure the ChromeDriver executable is accessible in the system’s PATH or provide the explicit path to the executable when initializing the ChromeDriver.
How to capture network traffic and analyze requests/responses with ChromeDriver?
It provides the capability to capture the browser’s network traffic using the Chrome DevTools Protocol. One can easily enable network logging and access network data, such as request and response headers, status codes, and timings, for analysis and debugging purposes.
How can I handle browser cookies and manage sessions with ChromeDriver?
ChromeDriver provides methods to handle browser cookies and manage sessions. You can use the add_cookie()
method to add cookies, get_cookies()
method to retrieve cookies, and delete_cookie()
or delete_all_cookies()
methods to remove cookies. By managing cookies, you can simulate different session states and test scenarios related to authentication, session management, and user preferences.
Got Questions? Drop them on LambdaTest Community. Visit now