Using Selenium with Python for Automated Testing

Sauce AI for Test Authoring: Move from intent to execution in second.|xBack to ResourcesBlogPosted August 24, 2024

Using Selenium with Python for Automated Testing

In this article, you & # x27; ll learn how to use Selenium with Python for automated testing. You will run a salmagundi of tests on a sample site to get a primal understanding of automated testing with these tools.

Documentation

Seleniumis a popular open source framework for automated testing of web applications across multiple browser, operating systems, and devices.

Selenium do it easier for developers to create automated tests for web applications without having to care about the fundamental technology. Before Selenium, testing a web coating was a time-consuming process. You had to manually perform different scenarios on several browsers to identify issues in the user experience.

The Selenium project proffer built-in support for 5 languages: Java, JavaScript, Python, C #, and Ruby. Python has the advantage of being, and it & # x27; s democratic among developer. It too offer potent built-in functions and an expansive ecosystem of libraries that make it easy to indite nearly any form of script, and it & # x27; s well-suited for test mechanisation.

Prerequisites

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

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

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

  • A to automate your testing process for multiple devices.

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

  • Selenium v4.6+

As of Selenium adaptation 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 instal Python, you experience to install the Selenium API for Python employ pip.

Open your terminal and run the next command:

pip install selenium

After instal Selenium, you can get writing your script.

1.The 1st step is to make a new Python handwriting. Open your favourite text editor and create a new file telephoneselenium_test.py. Then, import the Selenium library by add the following line of code to your book:

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 thewebdriverclass with additionalOptions. This class represents the web browser that will be used to run your tests. In this example, you & # x27; ll be using the Chrome web browser, so you need to create a new example of theChromeclass, and theOptionsclass described above allows web driver to run a browser illustration with extra capabilities.

The example below pose the driver to commence the web browser without the DevTools prompt:

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

Setting Optionsis not compulsory, but it makes the yield window much unclouded. 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 test.

3. With your drivertarget 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 & # x27; ll run your examination on the Sauce Labs demonstration website,SwagLabs.

In your code editor, write the following code inselenium_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 option for not prompting DevTools info
8
options = Options()
9
options.add_experimental_option(& quot; excludeSwitches & quot;,[& quot; enable-logging & quot;])
10
11
print(& quot; testing started & quot;)
12
driver = webdriver.Chrome(options=options)
13
driver.get(& quot; https: //www.saucedemo.com/ & quot;)
14
sleep(3)
15
16
# Get page title
17
title = driver.title
18
19
# Test if rubric is correct
20
assert& quot; Swag Labs & quot;in title
21
print(& quot; TEST 0: ` title ` test legislate & quot;)
22
23
# Close the driver
24
driver.quit()

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

python selenium_test.py

Running the command above should produce the undermentioned output:

testing begin
TEST 0: ` title ` test passed

If the yield does not return anAssertionError, it indicates that the tests surpass successfully and the title of the demonstration website is correct.

Extending the Test Script

In this section, you & # x27; ll extend your playscript to essay the login functionality of the demonstration site. To do this, you & # x27; ll involve to grab the input box and submit button of the web page by inspecting its situation elements. Right-click the page and select theInspectcard option to see anElementstab in the right pane of the browser window, as show in the image below:

Swag Labs Login

This superman is called DevTools. With it open, grab theid or classattributes of the input boxes on the web page, look on the elements you want to prove. Click the icon in the top-left corner of the DevTools Elvis, then select constituent on the web page. The corresponding code of the element will automatically foreground 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 theusername and passwordfields and populate them with appropriate credential. You & # x27; ll then programmatically click the login button, which can easily be done after take the push using itsid.

To begin indite the script, create a new file namedtest_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 theOptionsclass for yourwebdriverand initiate Chrome WebDriver, as present in the code below. Thiswebdriveris responsible for rendering the browser window:

1
# Set options for not motivate DevTools info
2
options = Options()
3
options.add_experimental_option(& quot; excludeSwitches & quot;,[& quot; enable-logging & quot;])
4
5
print(& quot; testing commence & quot;)
6
driver = webdriver.Chrome(options=options)

Next, you must add the codification below to open the demo website and begin your testing process. After opening the web page, the performance of the script halts for three moment using thesleep(3)purpose so that all the ingredient in the web page loading all in the browser:

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

1
driver.get(& quot; https: //www.saucedemo.com/ & quot;)
2
sleep(3)

In the code block below, you usefind_element () and the Byclass in conjunction to snaffle theusername and passwordfields. TheBycategory is used to easily locate elements on the web page throughclass, id, and xpath. After getting the fields, you use thesend_keys ()function to populate the field with credentials. You then use thefind_element ()function to get the login button and use theclick()function for the button to induct the login summons:

1
# Find element use element & # x27; s id attribute
2
driver.find_element(By.ID,& quot; user-name & quot;).send_keys(& quot; standard_user & quot;)
3
driver.find_element(By.ID,& quot; password & quot;).send_keys(& quot; secret_sauce & quot;)
4
driver.find_element(By.ID,& quot; login-button & quot;).click()
5
sleep(5)

To test whether the login was successful, you can check if the resulting web page wads as expected. In the code below, you assert that the element withtitle as its classattribute contains the string & quot; ware & quot;. If the assert is wrong, your string will drop anAssertionError. After performing the test, you have to quit the driver to release any remembering give by the browser window:

1
text = driver.find_element(By.CLASS_NAME,& quot; title & quot;).text
2
3
# Check if login was successful
4
assert& quot; products & quot;in text.lower()
5
6
print(& quot; TEST PASSED: LOGIN SUCCESSFUL & quot;)
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 act as expected.

Note: Using sleepis generally not considered a better practice, and was done hither for simpleness & # x27; s sake.The WebDriverWait biddingis the proper way to go.

Testing Add/Remove Buttons

In this subdivision, you & # x27; ll extend your script to include two more tests. These will test the buttons for adding and remove items from the cart.

Open the test_demo.pyfile and add the code below before thedriver.quit ()statement. First, add a test that grabs all the & quot; Add to Cart & quot; button and clicks a certain figure of buttons:

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

The codification above uses thefind_elements ()function alternatively offind_element ()to snaffle a list of elements withbtn_inventory as the CLASS_NAME.

Now, you have to test the assertion that thecart_valueis three after click the three buttons inadd_to_cart_btns:

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

In the above code, you retrieve the element with the category nameshopping_cart_badgeand check if it contains the text & quot; 3 & quot;, which would indicate that three items were successfully added to the handcart.

To test the remove from cart button functionality, add the next code to your Selenium handwriting:

1
print(& quot; test remove from cart & quot;)
2
remove_btns= driver.find_elements(By.CLASS_NAME,& quot; btn_inventory & quot;)
3
for btns inremove_btns[:2]:
4
btns.click()
5
assert& quot; 1 & quot;incart_value.text
6
print(& quot; TEST PASSED: REMOVE FROM CART & quot;,& quot; \n & quot;)

The code habituate thedriver.find_elementsmethod again to place all thebtn_inventoryelements on the page, and clicks the initiatory two of them. It so control if theshopping_cart_badgeelement contains the schoolbook & quot; 1 & quot;, which would betoken that two items were successfully removed from the cart. The code prints a success substance if both of these chit pass.

The script above footrace on your machine with a local browser, which is sufficient for learning the basics. However, testing an intact website topically isn & # x27; t scalable -- if it & # x27; s on your work laptop, you can & # x27; t do anything else while the tests are running. This is one of the ground why testing should be done on a cloud-based testing platform like.

A cloud-based examination platform lets you manage, run, and analyze the results of tests on a wide range of browser and platforms on remote servers sooner than on your local ironware. It also ensures that the results are dependable and reproducible, even when running declamatory number oftest in latitude.

A solution like Sauce Labs allows you to:

  • Run tests in analogue on multiple exam machines to speed up exam execution

  • Test across a range of environments, include different run scheme, browser, and devices

  • in real clip

  • Work together on testing task with collaborationism and sharing puppet

  • Easily adjust the number of test machine and other testing resourcefulness for best scalability and flexibleness

To use Sauce Labs for your current Selenium handwriting, you feature to create some changes to your file. Before making any changes, replicate the on-demand URL from theUser Settingssection in your Sauce Labs dashboard.

Sauce Labs provides hundreds of devices and browser edition on which to run your exam. It also offers a to render impost options for your Selenium WebDriver. The image below shows renderOptionsfor macOS Ventura with Safari 16:

Platform Configurator showing MacOS & Safari

Copy these options and paste them into your Selenium handwriting. Next, supply the build ID and tryout gens of your choice and replace theurlwith the on-demand URL you copied originally. The final file should appear something like this:

1
<scriptsrc="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
examination 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 besides get additional info about the tests from Sauce Labs, including screenshots, picture recording, logs, and dictation account. Go to theTest Resultssection in your Sauce Labs splasher 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 covering. You tested a demo website by asserting its title and then expanded on the script to screen the internal functionality of the web application.

You also acquire how to accommodate your handwriting to act on the cross-browser cloud test program, and you ran a Selenium book using Sauce Labs & # x27; built-in.

Using a cloud-based cross-browser try platform like Sauce Labs makes it easy to run tests on a wide-eyed orbit of browser and platform. Sauce Labs & # x27; reliable and stable platform also helps ensure that test results are true and consistent, even for bombastic numbers of exam.

Diego Molina

Staff Software Engineer at Sauce Labs

Published:
Aug 24, 2024
Jump to content

Prerequisites

Getting Started with Selenium

Extending the Test Script

Testing Login Functionality

Testing Add/Remove Buttons

Using a Cloud-Based Testing Platform

Share this post
Copy Share Link

Ready to start testing with Selenium and Sauce Labs?

Let & # x27; s go!

LinkedIn
© 2026 Sauce Labs Inc., all right allow. SAUCE and SAUCE LABS are register stylemark own by Sauce Labs Inc. in the United States, EU, and may be registered in other jurisdictions.
robot
quote

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