Selenium Python Tutorial: Getting Started With Pytest

Himanshu Sheth

Posted On: May 5, 2020

15 Min

According to the Developer Survey 2019 by StackOverflow, Python is considered to be the fastest-growing programming language. Though PyUnit (or UnitTest) is the default Selenium test automation framework in Python, many developers and testers prefer the Pytest framework.

In this introductory article of the Selenium Python tutorial series, I’ll give you a brief look at the basics of the Pytest framework. Below is the gist of the topics that I’ll cover in this Selenium Python tutorial.

Overview

What Is pytest?

pytest is a Python testing framework that lets you write and run tests with simple syntax, clear reporting and strong plugin support.

How pytest Identifies Test Files and Methods?

pytest uses simple naming rules to discover which files and functions should be executed as tests. It scans your project, picks up matching files and runs only the methods that follow its test naming pattern.

  • File Naming: Pytest treats any file named test_*.py or *_test.py as a test file.
  • Test Method Naming: A method must start with test to be recognized and executed.
  • Auto-Discovery: These rules allow pytest to find test modules and test functions without extra configuration.

How to Run Selenium Tests With pytest?

Selenium can be integrated with pytest to create clear, modular tests. The steps below outline how to prepare your setup and execute browser actions through pytest.

  • Environment Setup: Install Python, set up a virtual environment and add Selenium and pytest through pip.
  • Driver Configuration: Download the required browser driver or use tools like webdriver-manager to manage it automatically.
  • Test File Creation: Create a Python test file that initializes WebDriver and defines browser interactions as test functions.
  • Fixture Setup: Add pytest fixtures to handle WebDriver setup and teardown for clean, reusable test flows.
  • Execution: Run tests with the pytest command and verify results through the test output and browser behavior.

Introduction To Pytest Framework

Pytest is a popular Python testing framework, primarily used for unit testing. It is open-source and the project is hosted on GitHub. pytest framework can be used to write simple unit tests as well as complex functional tests.

It eases the development of writing scalable tests in Python. Unlike the PyUnit (or unittest) framework, tests written using pytest are expressive, compact, and readable as it does not require boiler-plate code.

In our recent LinkedIn poll, we asked the developer community about their preferred Python testing frameworks. A significant number of respondents favored Pytest for its simplicity and powerful features. These insights not only reflect the growing popularity of Pytest in the Python ecosystem but also underscore the importance of choosing the right tools for efficient testing.

python poll

Source

Selenium testing with Python & pytest is done to write scalable tests for database testing, cross browser testing, Pytest API testing, and more. It is easy to get started with pytest, as the installation process is very simple.

pytest framework is compatible with Python 3.5+ and PyPy 3. The latest version of pytest is 5.4.1.

To know more about pytest you can visit pytest website and pytest GitHub repository.

Below are some of the interesting facts about pytest obtained from the project’s GitHub repository:

facts about pytes

Advantages Of pytest Framework

Here are some of the primary advantages of Selenium testing with Python & pytest:

  • It can be used for simple as well as complex functional test cases for applications and libraries.
  • Existing Python code that uses other Python testing frameworks can be ported easily to pytest.
  • The Selenium test automation framework can be used for projects that practice TDD (Test Driven Development) as well as open-source projects.
  • Switching to the pytest framework is easy as it is compatible with other Python test frameworks such as PyUnit (or unittest) and Nose2.
  • Parameterization is supported in pytest which helps in execution of the same test with different configurations using a simple marker.
  • Availability of fixtures makes it easy for common test objects to be available throughout a module/class/session/function.

In this pytest tutorial, learn how to use parameterization in pytest to write concise and maintainable test cases by running the same test code with multiple data sets.

This PyTest Tutorial for beginners and professionals will help you learn how to use Python & pytest for performing Selenium automation testing.

Getting Started With Selenium Testing With Python & pytest

As pytest is not a part of the standard Python library, it needs to be installed separately.

In case you are new to pytest framework checkout this video to know more about pytest framework & its installation.

To install pytest, you have to execute the following command on the terminal (or command prompt) that makes use of the Python package manager (pip):

The following command should be executed to verify the status of the installation

Here is the output when the installation is performed on the Windows 10 machine:

selenium-testing-with-python

PyCharm is the most popular IDE for development using the Python language. Depending on the requirement, you can opt for the Community version or the Professional version. The community version of PyCharm is free and open-source; the same can be downloaded from PyCharm official download link.

Once the PyCharm installation is complete, it is necessary to set the default test runner as pytest. Navigate to File? Settings ?Tools ? Python Integrated Tools and select pytest to make it the default test runner.

pytest-tutorial

As pytest will be used for automated browser testing, we also have to install the Selenium package for Python. Selenium for Python can be installed by executing the following command on the Windows terminal (or prompt) or on the terminal of PyCharm.

selenium-testing-with-pytest

With this the environment setup for Selenium testing with Python & pytest (including automated browser testing) is complete.

You can watch this video to learn how to write and run your first test in pytest using Selenium.

Prerequisites For Selenium Testing With Python & pytest

For using Python & pytest, you need to install Python on your machine. Python for Windows can be downloaded from here. Along with Python 3.5+, pytest is also compatible with PyPy3. Prior knowledge of Python will be helpful in getting started with Selenium automation testing with pytest.

Since pytest will be used for automated browser testing, Selenium WebDriver for the browser under test needs to be installed. Download links for Selenium WebDriver for popular browsers is below:

Browser
Download location
Opera
https://github.com/operasoftware/operachromiumdriver/releases
Firefox
https://github.com/mozilla/geckodriver/releases
Chrome
http://chromedriver.chromium.org/downloads
Internet Explorer
https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver
Microsoft Edge
https://blogs.windows.com/msedgedev/2015/07/23/bringing-automated-testing-to-microsoft-edge-through-webdriver/

It is always a good practice to install the WebDriver for the corresponding web browser in the location where the browser executable (.exe) is present. By doing this, you do not have to specify the WebDriver path when instantiating the browser.

chromedriver-location

How pytest Identifies The Test Files And Test Methods

Executing the pytest command (without mentioning a filename) on the terminal will run all the Python files that have filenames starting with test_* or ending with *_test. These files are automatically identified as test files by the pytest framework.

The framework also mandates that the test methods should start with ‘test’ else the method will not be considered for execution. Below are two mandatory requirements for test code for Selenium testing with Python & pytest.

These are mandatory requirements as pytest has features built-in to the framework that supports auto-discovery of test modules and test methods (or functions).

Running Your First Selenium Test Automation Script With Python & pytest

To demonstrate Selenium testing with Python & pytest, I’ll test the LambdaTest ToDo App scenario for this Selenium Python tutorial:

  1. Navigate to the URL https://lambdatest.github.io/sample-todo-app/
  2. Select the first two checkboxes
  3. Send ‘Happy Testing at LambdaTest’ to the textbox with id = sampletodotext
  4. Click the Add Button and verify whether the text has been added or not

The implementation file (Sample.py) can be located in any directory as the invocation will be done using the filename.

Implementation

Code Walk-Through

Step 1 – The necessary modules are imported, namely pytest, sys, selenium, time, etc.

Step 2 – The test name starts with test_ (i.e. test_lambdatest_todo_app) so that pytest is able to identify the test. Using the Selenium WebDriver command, the Chrome WebDriver is instantiated. The URL is passed using the .get method in Selenium.

Step 3 – The Inspect Tool feature of the Chrome browser is used to get the details of the required web elements i.e. checkboxes with name li1 & li2 and button element with id = addbutton.

Once the web elements are located using the appropriate Selenium methods [i.e. find_element_by_name(), find_element_by_id()], necessary operations [i.e. click(), etc.] are performed on those elements.

Step 4 – The close() method of Selenium is used to release the resources held by the WebDriver instance.

Execution

The following command is executed on the terminal after navigating to the directory that contains the test code.

Using –verbose, the verbosity level is set to default. The –capture=no is used to capture only stderr and not stdout.

For adding more options to the pytest command, you can execute the –help option with pytest.

Here is the snapshot of the test execution in progress:

pytest-execution-script

lambdatest-sample-app1

Also Read: Using PyUnit For Selenium Test Automation

This certification is for professionals looking to develop advanced, hands-on expertise in Selenium automation testing with Python and take their careers to the next level.

Here’s a short glimpse of the Selenium Python 101 certification from LambdaTest:

Wrapping It Up

In this introductory article of the ongoing Selenium Python tutorial series, I gave you a brief look at Selenium Python testing & pytest. pytest is one of the most popular Selenium test automation frameworks in Python.

We also demonstrated the usage of pytest framework with Selenium where the URL under test was LambdaTest ToDo App. pytest framework mandates a particular naming nomenclature for test methods and test files as it has auto-discovery of test modules and test methods.

The availability of fixtures and classes makes it an ideal framework for automation testing, including cross browser testing.

You should now be able to do Selenium Python testing with pytest.In case of any doubt, do reach out to us. Feel free to share this article with your peers and help us reach out to them. That’s all for now. Happy Testing!!!?

Frequently Asked Questions (FAQs)

How much Python coding is required for Selenium?

You should be comfortable with Python basics like functions, classes, loops, and exceptions. As you move into more advanced automation, you’ll use concepts like decorators, virtual environments, and modular project structures.

What is Behave in Selenium Python?

Behave is a BDD framework for Python. It uses Gherkin feature files to describe behavior in plain English. Selenium handles browser automation, and Behave manages the step definitions and execution flow.

Can I learn Selenium using Python instead of Java?

Yes. Selenium works well with Python, and many testers prefer it because the syntax is clean and easy to learn. The Python ecosystem also offers helpful libraries for testing, reporting, and environment management.

Which Python version works best with Selenium?

Python 3.8 or higher is recommended. It’s stable, widely supported, and compatible with modern Selenium bindings and related testing tools.

Is Selenium Python suitable for mobile test automation?

Selenium itself focuses on web automation. For mobile apps, you can use Appium, which follows the same WebDriver protocol. This lets you apply your Selenium Python skills to Android and iOS testing.

How does Selenium Python handle dynamic elements or a changing DOM?

You can use WebDriverWait with expected conditions, custom wait functions, or flexible locators like dynamic XPaths and CSS selectors. These help your script wait for elements to load or stabilize.

Can Selenium Python tests be added to CI pipelines like Jenkins?

Yes. You can run Selenium Python tests in Jenkins, GitHub Actions, GitLab CI, and other CI/CD tools. Most teams trigger these tests automatically on pull requests or deployments.

What are the limitations of Selenium when using Python?

Selenium can’t solve Captchas or automate native OS dialogs. Intermittent failures, slow-loading pages, and browser differences can also create noise in test runs if not handled with proper waits and structure.

How do you maintain Selenium Python test scripts in large projects?

Use the Page Object Model, keep locators in separate modules, apply configuration management, and follow a clean project layout. Regular reviews and refactoring help keep the codebase steady as the app grows.

Is Selenium Python a good fit for end-to-end testing in agile teams?

Yes. Python integrates smoothly with tools like Pytest, which supports fixtures, plugins, and parallel execution. Combined with CI/CD, it works well for fast feedback cycles in agile environments.

Author

Himanshu Sheth is the Director of Marketing (Technical Content) at LambdaTest, with over 8 years of hands-on experience in Selenium, Cypress, and other test automation frameworks. He has authored more than 130 technical blogs for LambdaTest, covering software testing, automation strategy, and CI/CD. At LambdaTest, he leads the technical content efforts across blogs, YouTube, and social media, while closely collaborating with contributors to enhance content quality and product feedback loops. He has done his graduation with a B.E. in Computer Engineering from Mumbai University. Before LambdaTest, Himanshu led engineering teams in embedded software domains at companies like Samsung Research, Motorola, and NXP Semiconductors. He is a core member of DZone and has been a speaker at several unconferences focused on technical writing and software quality.

Blogs: 131

linkedintwitter