Selenium with Python Tutorial: Getting started with Test Automation

Selenium with Python Tutorial: Getting started with Test Automation

Developers prioritize implementing changes rapidly in an agile environment. When updating a front-end component, they must perform cross-browser testing. Web apps’ technological and functional capabilities have continuously increased over the years. Automated testing is necessary to ensure these functionalities and the UI function properly. According to the Stack Overflow Developer Survey in 2021, Python is placed third among programming languages, trailing only JavaScript and HTML/CSS. With Selenium being the most used tool for automated testing, the combined capabilities of Selenium and Python aid in automating interactions with Web Elements in the Document Object Model.

Let us learn more about the Selenium Python binding with integrated Python Selenium examples for a better understanding. Transform your automation solution with the extensive Selenium Python tutorial below!

What is Selenium?

Selenium is a lightweight, open-source automation testing framework for web applications. It supports a number of browsers, including Safari, Firefox, Chrome, and Internet Explorer. Additionally, it may mimic behaviors like clicking links, completing forms, and making purchases on a website.

To test online applications, Selenium can automate web browser interaction. Selenium is frequently used with other software testing tools like JUnit or TestNG to generate thorough automated tests for online applications.

Selenium can also automatically test web applications for functionality and performance. Furthermore, Selenium can produce reports or automatically scrape data from websites. The fact that Selenium is an open-source technology gives it a significant edge over other testing tools in that there are no license fees.

Additional elements influencing Selenium’s growing popularity include –

  • You can develop a test script in any programming language: Python, Java, Ruby, C#, Perl, PHP, and .Net.
  • Windows, Mac, and Linux are the three supported operating platforms for testing.
  • It provides continuous testing through the use of Jenkins, Maven, and Docker.
What is Selenium?

What is Python?

Python is a versatile programming language that has become increasingly popular in recent years. Unlike some other languages, Python is relatively easy to learn and can be used for a wide variety of tasks. For example, Python is often used for web development, scientific computing, artificial intelligence, and even video games. 

Despite its flexibility, Python remains a concise and readable language that programmers of all levels of experience admire. In addition, the Python community is large and supportive, making it an ideal choice for those just starting in the programming world. Whether you’re looking to build a new website or create the next blockbuster game, Python is worth considering as your go-to language.

Python is a widely used high-level interpreted language. Known for its ease of use and readability, Python has recently gained popularity for its Selenium bindings, which allow WebDrivers to be controlled by Python code. You can find Python Selenium example code easily online. 

Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, Chrome, Edge, etc. These bindings enable you to create concise and reliable tests with little code. As a result, Python has become a popular choice for automating web browser testing.

Why do we Use Selenium and Python for Automation Testing?

Selenium has a powerful toolkit that firmly supports the rapid development of test automation for online applications. It provides a selection of testing features that meet the needs of web application testing. Python, on the other hand, is an object-based, high-level scripting language designed specifically for simple interpretation.

Some of the reasons why Selenium Python automation testing is more convenient are –

  • It is easy to read, easy to code, and runs rapidly.
  • The Python API makes it easier to connect to the browser using Selenium. Python Selenium bonding provides straightforward APIs for conducting practical and functional tests on Selenium WebDriver effectively.
  • Python is a computer language that is extremely user-friendly and less verbose than other programming languages. The Python API enables you to use Selenium to communicate with the browser. Regardless of how a browser is designed, Selenium can easily communicate common Python commands to many browsers.
  • Selenium Python is a relatively easy library to use.
  • Selenium with Python has a wide range of tools to extend it. As a result, the WebDriver is a strong binding for Python.

Selenium with Python

Two ways to run Selenium test scripts with the help of Python:

Using Selenium WebDriver:

Selenium WebDriver is a tool that allows web browsers to be automated. Selenium WebDriver can be used with Python to create test scripts that interact with web pages and test their functionality. To utilize Selenium WebDriver with Python, use pip to install the Selenium package. You can then build an instance of the WebDriver class and use it to interact with online sites by clicking buttons, filling out forms, and traveling to various pages. Once you’ve written it, you can run your test script using Python’s built-in unit test framework or any other testing framework of your choice.

Using Selenium IDE:

Selenium IDE is a browser plugin that allows you to record and replay web page interactions. The recorded test scripts can also be exported in various computer languages, including Python. To run Selenium test scripts exported from Selenium IDE, install the Selenium package using pip and import the required modules into your Python script. You can run the exported test script using Python’s built-in unit test framework or any other testing framework. Because you can record your interactions with web pages rather than writing the code manually, using Selenium IDE can be a faster approach to writing test scripts. Unfortunately, it may not be as flexible or robust as simply utilizing Selenium WebDriver.

Why Choose Python Over Java in Selenium?

Java is a versatile and powerful programming language that enables developers to create sophisticated applications. Java is used in various settings, from Android apps to server-side web applications. One of the key advantages of Java is its portability, which means that Java programs can run on any platform that supports the Java Virtual Machine. 

Additionally, Java is well-suited for creating embedded systems and large-scale enterprise applications. As a result, Java is one of the most popular programming languages in use today. While Java is an excellent choice for many applications, it is not the only option available. However, based on the key criteria for choosing a programming language on the basis of simplicity, Python is the most used language, according to this survey, after HTML.

With Selenium automation testing with Java, there are several advantages, like –

  • Given that Java is a more popular and well-liked programming language, combining Java with Selenium automation testing becomes simpler.
  • With big community support, you can write test cases simply.
  • Because Java applications run more quickly, testing execution can be done more adaptively.

Now, why do programmers choose Selenium WebDriver Python over Java programming language?

Why do Programmers Choose Selenium WebDriver Python Over Java Programming?

Compared to other programming languages, it has the least complicated grammar. Thus, the Selenium Python ChromeDriver is the easiest and safest choice over complicated automation testing.

Using Python instead of Java for Selenium testing has several benefits. They are –

  • Python is an easy and productive language.
  • Python is relatively simple, easy to install, and runs faster than Java.
  • Selenium facilitates the Python API’s connection to the browser. By judiciously employing Selenium WebDriver Python, the Python and Selenium intersection provides a simple API for writing functional tests.
  • Python is supported on almost all platforms, including Windows, Linux, and Mac. This suggests that there is a very low learning curve, and thus makes it easier to write Selenium automation scripts.
  • The Python syntax command makes Python codes highly legible and clear.
  • Testers can create effective automation scripts for the automated test suite by using the extensive standards provided by the Python libraries.

Prerequisites to Run Selenium Tests with Python

Selenium libraries are not installed as a default when you install Python. The pip installer is the simplest method for installing Selenium in Python. Open a command line, go to the location where Python is installed, and type “pip list” to see if Selenium libraries are already installed in your Python. This command will list the libraries that are presently available in the Python installation.

Prerequisites to Run Selenium Tests with Python

PIP stands for Preferred Installer Program. PIP and Python are installed by default. We need to run a command – pip install Selenium in order to bind/install all of the necessary Selenium libraries with Python.

Once the command is executed, the following will download and install the Selenium libraries.

Prerequisites to Run Selenium Tests with Python

Now use the pip list command to check the Selenium libraries.

Prerequisites to Run Selenium Tests with Python

While Selenium’s installation makes the feature accessible, extra drivers are required to communicate with a particular web browser. You may find the links to get the drivers for Microsoft Edge, Google Chrome, Firefox, and Safari according to your device compatibility.

It should be sufficient to download the installation package and plugins if you simply intend to test Selenium locally. However, you would also be required to download the Selenium Server and install it if you want to set up Selenium Python automation on a distant server.

How to Run your First Selenium Tests with Python?

Once you complete the prerequisites to run Selenium tests with Python, let us start with the first test in Python Selenium automation.

Step 1 – First, import the Selenium classes for WebDriver and Keys.

Selenium Tests with Python - 1

You can connect to a browser instance using the WebDriver class, which we’ll discuss in more detail later. You may simulate keyboard keystrokes, including those for specific keys like “Return” and “Shift” using the Keys class.

Step 2 – Create a Chrome instance using the driver’s path that you downloaded from the corresponding browser’s website.

In this case, we’ll assume that the Python script you’ll run and the driver are both located in the same directory.

Selenium Tests with Python -2

This launches a local Chrome instance for testing purposes on the local computer. This command allows you to test it till you deploy the .close() method to seize the connection to the browser.

Step 3 – Next, load a website using the driver.get() method.

Alternatively, you can launch a local development site by opening a Chrome window on your computer, entering the URL, and pressing Use. The .get() method waits until a website has finished rendering before continuing to the next stage and starting the loading process.

Selenium Tests with Python -3

Step 4 – Using the .title attribute, you can obtain the textual title of the webpage once the page has loaded correctly.

You can use assert and if statements to check if a particular substring appears in the title.Example – For printing the title of the page

Selenium Tests with Python-4

The output would be –

step 4 - output

In the case of Python interpreters, the Google Chrome browser window will still be open while running the test. Additionally, Chrome displays a notification stating that automatic software is currently in charge.

Step 5 – pick the component from the HTML DOM, type a value in it, and then simulate pressing the Return key to submit the form.

You can choose the element based on its CSS class, ID, name attribute, or tag name. If you look at the query search bar’s source, you’ll see that this DOM element’s name attribute is “q.” As a result, to choose the element, use the .find_element_by_name method, as shown below.

Selenium Tests with Python -5

Step 6 – With the DOM element selected, use .clear() to clear the contents, .send_keys() to send a string as the value, and Keys.RETURN to emulate pressing the Return key.

Selenium Tests with Python -6

Moreover, these actions change the URL in a specific way. To confirm the ongoing URL, use the given command – print(driver.current_url)

To stop the ongoing session, use .close() to disconnect the browser link.

Using the Python Selenium example above, we have learned how to run the first test using Selenium and Python.

Navigate through HTML DOM Elements

After completing our initial Selenium WebDriver Python test, let’s examine the various choices for selecting and interacting with DOM elements.

For example, a search bar queried for a specific string.

The HTML shows as – <input id=”id-search-field” name=”q” type=”search” role=”textbox” class=”search-field” placeholder=”Search” value=”” tabindex=”1″>

In the above example, we used the .find_element_by_name() method to search for the attribute name within the HTML tag input. However, you can also use other relevant methods like

  • CSS ID: .find_element_by_id(“id-search-field”)
  • DOM Path: .find_element_by_xpath(“//input[@id=’id-search-field’]”)
  • CSS class: .find_element_by_class_name(“search-field”)

Although every element has a unique CSS ID by design, searching by class name may return more than one result. Additionally, you can be sure of what you are looking for when you search along the element’s DOM route.

Navigate through Windows and Frames

When using your web application, you might need to interact with several windows and frames. Working on separate windows is frequently used for file uploads and social logins. You can switch to a new window and perform different operations by using the driver’s .switch to window() method.

The code required to open a new window goes as – driver.switch_to_window(‘window_name’)

A window handle, which is used to identify each open window in your driver specifically, might be used if the value is not kept in the specific target attribute. Run these commands to see the list of the window handles –

Navigate through Windows and Frames -1

In the same way, you can switch your focus to a frame within an open window by using .switch_to_frame(). Following the completion of relevant actions, run the given command to switch back to the primary window.

Navigate through Windows and Frames -2

Work with Idle Time During a Test

While you have examined many tests in static web apps, there may be situations in which you must wait a certain amount of time before acting in a single-page application.

Primarily, Selenium possesses two types of waitsimplicit waits and explicit waits. An implicit wait allows the driver to wait for a particular time, while an explicit wait makes the driver wait for a specific action until completion.

It is necessary to employ a try-finally block when using an explicit wait since, in the worst-case situation, it can make your test stuck. Essentially, you give the driver a time limit and a specific element to wait for before completion.

To start with, use WebDriverWait() function to command your driver to halt for a specific amount of time. Through the By.ID method of the expected_conditions class, one can query for the presence of a new element.

Work with Idle Time During a Test

How to Integrate Selenium with Python Unit Tests?

Let’s look at how Selenium tests can be integrated into Python units. In this case, we will deploy Python’s unit test module –

How to Integrate Selenium with Python Unit Tests?

(Code is for reference only)

In this, you need to begin the unit test class using the .Chrome() method and arrange for the driver object. In the single unit test we demonstrate, we enter the identical text into the search field and compare the obtained URL with the URL observed previously. Separate test modules can also be written for different browsers, so you can use the same functionality again.

How to Create Test Scripts in Selenium with Python?

Selenium Python Example 1 – Automation for ‘Facebook log-in page’ using Selenium Python ChromeDriver.

The Python code below employs the Selenium package to automate logging into Facebook with a given email address and password.

How to Create Test Scripts in Selenium with Python?

Let’s go through each line of the code and explain what it does:

  1. from selenium import webdriver: Imports the Selenium library’s webdriver module, providing methods for controlling web browsers with Python code.
  2. from selenium.webdriver.common.keys import Keys: Imports the webdriver’s Keys class. common, such as RETURN, that can be passed to web components.
  3. user_name = “YOUR EMAILID”: Provides the user name variable a string value that should be substituted with a genuine Facebook email address..
  4. password = “YOUR PASSWORD”: Gives the password variable a string value that should be substituted with an actual Facebook password.
  5. driver = webdriver.Firefox(): Creates a new Firefox WebDriver object to launch a browser window and programmatically control it.
  6. driver.get(“”): Loads the Facebook login page into the browser window.
  7. element = driver.find_element_by_id(“email”): Locates the HTML input element with the ID attribute “email” and assigns it to the element variable using the driver’s find element by id method.
  8. element.send_keys(user_name): Use the element object’s send keys method to enter the value of the user name variable into the email input field.
  9. element = driver.find_element_by_id(“pass”): Locates the HTML element with the ID attribute “pass” and assigns the element variable.
  10. element.send_keys(password): To enter the value of the password variable into the password input field, use the element objects send keys method.
  11. element.send_keys(Keys.RETURN): Submits the login form by handing in the RETURN key constant.
  12. driver.close(): Ends the WebDriver session.

When the code is executed with the correct Facebook credentials, it will automatically log the user into his or her Facebook account.

(Image is for reference only)

Output –


(Image is for reference only)

Selenium Python Example 2 – Login into Facebook & Inspect Title

We will use Selenium to automate the Facebook login process in this example.

  • First, we import the Selenium packages that are required.
  • After that, we start Firefox by creating a WebDriver object.
  • Then, we travel to the Facebook login page by invoking the get function on our WebDriver object with the login page’s URL.
  • Using their HTML element IDs, we then locate the username and password input forms, as well as the submit button.
  • We insert our email and password into the respective input areas using the send keys method.
  • After completing the login form, we use the click method to click on the submit button.
  • To wait for the next page to load, we construct a WebDriverWait object with a timeout of 5 seconds.
  • Finally, we capture the page title using the title attribute of the WebDriver object and assert that the page title matches “Facebook”.

Here is the code:

Selenium Python Example 2

The code is well-commented and easy to understand. It automates the login process for Facebook and checks that the page title is correct, a common task when testing web applications.

(Image is for reference only)


The Selenium Python automation framework is only as strong as the tests being designed, regardless of how much knowledge you have of how it works. During a test, automating the process can save a great deal of time, so it is important to create tests that cover all the possible scenarios. Detecting errors in the earlier testing phase is always better than ending customer complaints later.

The Testsigma platform is a free, open-source tool that can help with your test automation needs. By utilizing free maintenance tests and limitless flexibility, you can easily create automated tests without time-consuming setups, integrations, or programming. Use cloud-based solutions like Testsigma cloud to create an automation framework with the best user experience.

To provide a smooth cross-platform experience, conduct accurate and automated cross-browser testing on a real device. Since monitoring on Python Selenium automation network considers actual user circumstances, it assists in locating bottlenecks and delivering a smooth and uniform user experience across various platforms, devices, and browsers.

Frequently Asked Questions

How do I write a Selenium script?

Selenium scripts are written in a special scripting language, which allows users to create custom test scenarios. To write a Selenium script, users need to have a basic understanding of the scripting language. Additionally, users should be familiar with the structure of the web application being tested.

Once these two requirements are met, writing a Selenium script is simply a matter of following the scripting language’s proper syntax and grammar rules. With a little practice, anyone can become an expert at writing Selenium scripts.

Why is Selenium mostly used?

Selenium WebDriver is a tool used for automating web application testing. It simulates how a user interacts with a website. Selenium WebDriver can be used for functional, regression, and end-to-end testing.

Selenium WebDriver is mostly used because it supports multiple browsers, is open source, and has good community support. In addition, Selenium can be integrated with other tools, such as Jenkins and TestNG, for better results. Therefore, Selenium is the tool of choice for many software testing professionals.

Which language is best for Selenium?

While you can use several languages for Selenium WebDrivers, there are some clear advantages to using Python. First, Python is a very concise and readable language, which makes it easy to write Selenium tests.

Second, Python has a large and active community of developers, which means that many resources are available for learning the language and troubleshooting any problems you may encounter. Finally, Python is widely used in the field of test automation. For all these reasons, Python is an excellent choice for Selenium web development.

Suggested Reading

Selenium 4 – What to Expect?

Selenium Alternatives for Automated Regression Testing

Selenium Standalone Server VS Selenium Server

Selenium Alternatives

Selenium and Mobile Test Automation

Selenium VS Testsigma

Test automation made easy

Start your smart continuous testing journey today with Testsigma.



Power of POC in Testing: Your Exclusive Guide to Success
Power of POC in Testing: Your Exclusive Guide to Success
performance testing tools_banner image
Test objects in software testing | Types & How to Create it?
How To Write Calculator Test Cases With Sample Test Cases
How To Write Calculator Test Cases? With Sample Test Cases