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.
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.
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:
1from selenium import webdriver2from selenium.webdriver.chrome.options import Options3from 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:
1options = Options()23options.add_experimental_option(& quot; excludeSwitches & quot;,[& quot; enable-logging & quot;])4driver = 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:
1from selenium import webdriver2from selenium.webdriver.chrome.options import Options34from time import sleep567# Set option for not prompting DevTools info8options = Options()9options.add_experimental_option(& quot; excludeSwitches & quot;,[& quot; enable-logging & quot;])1011print(& quot; testing started & quot;)12driver = webdriver.Chrome(options=options)13driver.get(& quot; https: //www.saucedemo.com/ & quot;)14sleep(3)1516# Get page title17title = driver.title1819# Test if rubric is correct20assert& quot; Swag Labs & quot;in title21print(& quot; TEST 0: ` title ` test legislate & quot;)2223# Close the driver24driver.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:

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:

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:
1from selenium import webdriver2from selenium.webdriver.chrome.options import Options3from selenium.webdriver.common.by import By45from 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 info2options = Options()3options.add_experimental_option(& quot; excludeSwitches & quot;,[& quot; enable-logging & quot;])45print(& quot; testing commence & quot;)6driver = 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.
1driver.get(& quot; https: //www.saucedemo.com/ & quot;)2sleep(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 attribute2driver.find_element(By.ID,& quot; user-name & quot;).send_keys(& quot; standard_user & quot;)3driver.find_element(By.ID,& quot; password & quot;).send_keys(& quot; secret_sauce & quot;)4driver.find_element(By.ID,& quot; login-button & quot;).click()5sleep(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:
1text = driver.find_element(By.CLASS_NAME,& quot; title & quot;).text23# Check if login was successful4assert& quot; products & quot;in text.lower()56print(& quot; TEST PASSED: LOGIN SUCCESSFUL & quot;)78# Close the driver9driver.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:
1print(& quot; testing add to cart & quot;)2add_to_cart_btns= driver.find_elements(By.CLASS_NAME,& quot; btn_inventory & quot;)34# Click three button to make the cart_value 35for btns inadd_to_cart_btns[:3]:6btns.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:
1cart_value= driver.find_element(By.CLASS_NAME,& quot; shopping_cart_badge & quot;)2assert& quot; 3 & quot;incart_value.text3print(& 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:
1print(& quot; test remove from cart & quot;)2remove_btns= driver.find_elements(By.CLASS_NAME,& quot; btn_inventory & quot;)3for btns inremove_btns[:2]:4btns.click()5assert& quot; 1 & quot;incart_value.text6print(& 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:

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:
1examination started2TEST PASSED: LOGIN SUCCESSFUL34testing add to cart5TEST PASSED: ADD TO CART67testing remove from cart8TEST 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.
More Selenium Resources
Staff Software Engineer at Sauce Labs
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
Ready to start testing with Selenium and Sauce Labs?
Let & # x27; s go!
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 FreeTest 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

