Back to Resources

Blog

Posted August 24, 2024

Using Selenium with Python for Automated Testing

In this article, you'll learn how to use Selenium with Python for automated testing. You will run a variety of tests on a sample website to get a fundamental understanding of automated testing with these tools.

Selenium is a popular open source framework for automated testing of web applications across multiple browsers, operating systems, and devices.

Selenium makes it easier for developers to create automated tests for web applications without having to worry about the underlying technology. Before Selenium, testing a web application was a time-consuming process. You had to manually perform different scenarios on various browsers to identify issues in the user experience.

The Selenium project offers built-in support for 5 languages: Java, JavaScript, Python, C#, and Ruby. Python has the advantage of being easy to learn and versatile, and it's popular among developers. It also offers powerful built-in functions and an expansive ecosystem of libraries that make it easy to write nearly any kind of script, and it's well-suited for test automation.

Prerequisites

To follow this tutorial, you need these installed on your computer:

  • The latest version of Python. This tutorial uses Python 3.11, and you need a fundamental knowledge of Python programming to follow along.

  • VS Code (or PyCharm, other suitable IDE) to write and run scripts.

  • A free trial Sauce Labs account to automate your testing process for multiple devices.

  • A modern browser like Chrome, Edge, or Firefox. This tutorial uses Chrome.

  • Selenium v4.6+

As of Selenium versions 4.6, you no longer need to download the browser driver separately. The Selenium WebDriver employs a service object (Selenium Manager) to render a browser window, negating the requirement to download an external WebDriver.

Getting Started with Selenium

In addition to installing Python, you have to install the Selenium API for Python using pip.

Open your terminal and run the following command:

pip install selenium

After installing Selenium, you can begin writing your script.

1. The first step is to create a new Python script. Open your preferred text editor and create a new file called selenium_test.py. Then, import the Selenium library by adding the following lines of code to your script:

1
from selenium import webdriver
2
from selenium.webdriver.chrome.options import Options
3
from time import sleep

2. Next, create a new instance of the webdriver class with additional Options. This class represents the web browser that will be used to run your tests. In this example, you'll be using the Chrome web browser, so you need to create a new instance of the Chrome class, and the Options class described above allows web drivers to run a browser instance with additional capabilities.

The example below sets the driver to start the web browser without the DevTools prompt:

1
options = Options()
2
3
options.add_experimental_option("excludeSwitches", ["enable-logging"])
4
driver = webdriver.Chrome(options=options)

Setting Options is not mandatory, but it makes the output window much cleaner. You will, however, need to include the argument that the Chrome class should take a path to WebDriver, as Selenium uses it to initiate the browser window and perform the tests.

3. With your driver object set up, you can start the testing process by writing a simple script to test the title of a web page. For this tutorial, you'll run your tests on the Sauce Labs demo site, SwagLabs.

In your code editor, write the following code in selenium_test.py:

1
from selenium import webdriver
2
from selenium.webdriver.chrome.options import Options
3
4
from time import sleep
5
6
7
# Set options for not prompting DevTools information
8
options = Options()
9
options.add_experimental_option("excludeSwitches", ["enable-logging"])
10
11
print("testing started")
12
driver = webdriver.Chrome(options=options)
13
driver.get("https://www.saucedemo.com/")
14
sleep(3)
15
16
# Get page title
17
title = driver.title
18
19
# Test if title is correct
20
assert "Swag Labs" in title
21
print("TEST 0: `title` test passed")
22
23
# Close the driver
24
driver.quit()

4. To run this test, open your terminal and run the following command:

python selenium_test.py

Running the command above should produce the following output:

testing started TEST 0: `title` test passed

If the output does not return an AssertionError, it indicates that the tests passed successfully and the title of the demo website is correct.

Extending the Test Script

In this section, you'll extend your script to test the login functionality of the demo site. To do this, you'll need to grab the input boxes and submit button of the web page by inspecting its site elements. Right-click the page and select the Inspect menu option to see an Elements tab in the right pane of the browser window, as shown in the image below:

Swag Labs Login

This pane is called DevTools. With it opened, grab the id or class attributes of the input boxes on the web page, depending on the elements you want to test. Click the icon in the top-left corner of the DevTools pane, then select elements on the web page. The corresponding code of the element will automatically highlight in the DevTools pane, as shown in the image below:

Swag Labs in Chrome Dev Tools

Testing Login Functionality

To test the login functionality of the demo site, Selenium will locate the username and password fields and populate them with appropriate credentials. You'll then programmatically click the login button, which can easily be done after selecting the button using its id.

To begin writing the script, create a new file named test_demo.py. Add the following code to import the required modules that will be used by the script:

1
from selenium import webdriver
2
from selenium.webdriver.chrome.options import Options
3
from selenium.webdriver.common.by import By
4
5
from time import sleep

After importing the necessary modules, you must set the Options class for your webdriver and initiate Chrome WebDriver, as shown in the code below. This webdriver is responsible for rendering the browser window:

1
# Set options for not prompting DevTools information
2
options = Options()
3
options.add_experimental_option("excludeSwitches", ["enable-logging"])
4
5
print("testing started")
6
driver = webdriver.Chrome(options=options)

Next, you must add the code below to open the demo website and begin your testing process. After opening the web page, the execution of the script halts for three seconds using the sleep(3) function so that all the elements in the web page load completely in the browser:

1
driver.get("https://www.saucedemo.com/")
2
sleep(3)

In the code block below, you use find_element() and the By class in conjunction to grab the username and password fields. The By class is used to easily locate elements on the web page through class, id, and xpath. After getting the fields, you use the send_keys() function to populate the fields with credentials. You then use the find_element() function to get the login button and use the click() function for the button to initiate the login process:

1
# Find element using element's id attribute
2
driver.find_element(By.ID, "user-name").send_keys("standard_user")
3
driver.find_element(By.ID, "password").send_keys("secret_sauce")
4
driver.find_element(By.ID, "login-button").click()
5
sleep(5)

To test whether the login was successful, you can check if the resulting web page loads as expected. In the code below, you assert that the element with title as its class attribute contains the string "products". If the assert is wrong, your string will throw an AssertionError. After performing the test, you have to quit the driver to release any memory held by the browser window:

1
text = driver.find_element(By.CLASS_NAME, "title").text
2
3
# Check if login was successful
4
assert "products" in text.lower()
5
6
print("TEST PASSED : LOGIN SUCCESSFUL")
7
8
# Close the driver
9
driver.quit()

Running the above code should produce the following output:

$ python test_demo.py testing started TEST PASSED : LOGIN SUCCESSFUL

As you can see, the test passed, which means that the demo site is working as expected.

Note: Using sleep is generally not considered a best practice, and was done here for simplicity's sake. The WebDriverWait command is the proper way to go.

Testing Add/Remove Buttons

In this section, you'll extend your script to include two more tests. These will test the buttons for adding and removing items from the cart.

Open the test_demo.py file and add the code below before the driver.quit() statement. First, add a test that grabs all the "Add to Cart" buttons and clicks a certain number of buttons:

1
print("testing add to cart")
2
add_to_cart_btns = driver.find_elements(By.CLASS_NAME, "btn_inventory")
3
4
# Click three buttons to make the cart_value 3
5
for btns in add_to_cart_btns[:3]:
6
btns.click()

The code above uses the find_elements() function instead of find_element() to grab a list of elements with btn_inventory as the CLASS_NAME.

Now, you have to test the assertion that the cart_value is three after clicking the three buttons in add_to_cart_btns:

1
cart_value = driver.find_element(By.CLASS_NAME, "shopping_cart_badge")
2
assert "3" in cart_value.text
3
print("TEST PASSED : ADD TO CART", "\n")

In the above code, you retrieve the element with the class name shopping_cart_badge and check if it contains the text "3", which would indicate that three items were successfully added to the cart.

To test the remove from cart button functionality, add the following code to your Selenium script:

1
print("testing remove from cart")
2
remove_btns = driver.find_elements(By.CLASS_NAME, "btn_inventory")
3
for btns in remove_btns[:2]:
4
btns.click()
5
assert "1" in cart_value.text
6
print("TEST PASSED : REMOVE FROM CART", "\n")

The code uses the driver.find_elements method again to locate all the btn_inventory elements on the page, and clicks the first two of them. It then checks if the shopping_cart_badge element contains the text "1", which would indicate that two items were successfully removed from the cart. The code prints a success message if both of these checks pass.

The script above runs on your machine with a local browser, which is sufficient for learning the basics. However, testing an entire website locally isn't scalable--if it's on your work laptop, you can't do anything else while the tests are running. This is one of the reasons why testing should be done on a cloud-based testing platform like Sauce Labs.

A cloud-based testing platform lets you manage, run, and analyze the results of tests on a wide range of browsers and platforms on remote servers rather than on your local hardware. It also ensures that the results are reliable and consistent, even when running large numbers of tests in parallel.

A solution like Sauce Labs allows you to:

  • Run tests in parallel on multiple test machines to speed up test execution

  • Test across a range of environments, including different operating systems, browsers, and devices

  • Work together on testing projects with collaboration and sharing tools

  • Easily adjust the number of test machines and other testing resources for better scalability and flexibility

To use Sauce Labs for your current Selenium script, you have to make some changes to your file. Before making any changes, copy the on-demand URL from the User Settings section in your Sauce Labs dashboard.

Sauce Labs provides hundreds of devices and browser versions on which to run your tests. It also offers a platform configurator to generate custom options for your Selenium WebDriver. The image below shows generated Options for macOS Ventura with Safari 16:

Platform Configurator showing MacOS & Safari

Copy these options and paste them into your Selenium script. Next, supply the build ID and test name of your choice and replace the url with the on-demand URL you copied earlier. The final file should look something like this:

1
<script src="https://gist.github.com/vivekthedev/f8832087dd4da87f6b63750c8d0b4998.js"></script>

Run the test using the command below:

python test_demo.py

You should get the output below to show that the test worked as expected:

1
testing started
2
TEST PASSED : LOGIN SUCCESSFUL
3
4
testing add to cart
5
TEST PASSED : ADD TO CART
6
7
testing remove from cart
8
TEST PASSED : REMOVE FROM CART

You can also get additional information about the tests from Sauce Labs, including screenshots, video recordings, logs, and command history. Go to the Test Results section in your Sauce Labs dashboard to see the in-depth test analysis.

Wrapping Up

In this tutorial, you learned how to use Selenium with Python to run tests on web applications. You tested a demo site by asserting its title and then expanded on the script to test the internal functionality of the web application.

You also learned how to adapt your script to work on the cross-browser cloud testing platform Sauce Labs, and you ran a Selenium script using Sauce Labs' built-in platform configurator.

Using a cloud-based cross-browser testing platform like Sauce Labs makes it easy to run tests on a wide range of browsers and platforms. Sauce Labs' reliable and stable platform also helps ensure that test results are reliable and consistent, even for large numbers of tests.

Diego Molina
Staff Software Engineer at Sauce Labs
Published:
Aug 24, 2024
Share this post
Copy Share Link

Ready to start testing with Selenium and Sauce Labs?

Let's go!

© 2024 Sauce Labs Inc., all rights reserved. SAUCE and SAUCE LABS are registered trademarks owned by Sauce Labs Inc. in the United States, EU, and may be registered in other jurisdictions.