You would be hard pushed to work in testing without being, at least, aware of Selenium WebDriver. Selenium WebDriver is a great addition to any testers tool belt. It offers cross browser testing, for multiple languages and can be used in conjunction with your choice of framework and assertion library, what’s not to like? One thing which may put people off is the initial set up which is less user friendly than some of its counterparts. But never fear we’re here to help! 💪
In this post, we’ll look at how you can get started with web automation using Selenium WebDriver and Python. We’ll be writing a simple test and look at how we can install Python & Selenium and manage drivers.
For more chapters on Selenium Python web automation testing – Check out this great tutorial by the Automation Panda! 🐼🐍
In this example, we won’t be utilizing any frameworks and will instead focus on the core Selenium so as not to detract from how to use Selenium WebDriver (but you can also check out free solutions such as TestProject that is built on top of Selenium and is scheduled to release their Python SDK very soon!).
Table of Contents – Selenium Python Beginners Tutorial for Automation Testing
- Why Selenium Webdriver
- Why Python
- Installing Python
- Installing Selenium
- Writing our First Selenium Python Test
Before we dive in, let’s understand what makes Selenium WebDriver and Python a great choice.
Selenium is synonymous with UI automation testing. It has been the go-to open source tool for UI automation testing and it’s easy to see why. It packs a vast number of features that allow users to automate browser interactions just as if they were interacting with the web page themselves. Selenium is extremely versatile and can be married up with many frameworks, assertion libraries and even scripting languages, including Python. For all the recent updates coming up in Selenium 4 – You’ll find this article by Rex Jones II an interesting read!
Python has been around since the early 90’s but its popularity has grown exponentially in the past decade, partly due to the adoption of Python by the Data Science community and partly because it’s a great language for beginners. It has a simple syntax and at its core tries to promote clean and readable code. Python has a rich library of available packages and a hugely supportive and active community, not to mention some great automation testing frameworks. It is for these reasons that Python is a great choice for automation testing.
Ok cool, so now we understand why we may want to choose python, we can get started. First, let’s install Python. We will be using 3.8.2 (the latest version) for this demo but you should be able to follow along with any 3.X version.
Now I’m using Windows. If you’re on a Mac you may find you already have Python installed. To check simply type python -V into your Command Prompt/terminal. If installed, you should see something like this:
If not yet installed, you can download and install python here.
Once installed, rerun the Python -V command from your command prompt and you should see that python is now installed. Good job!
Right, now we have Python so we can go ahead and install Selenium. Best practice for Python is to create a virtual environment for your project and install any required packages there but for the purposes of this demo, we’ll be installing it globally on our system.
To do this we are going to use PIP, Pythons package management system and it couldn’t be simpler. Just run the following command in your command prompt:
Pip install selenium
It may take a minute, but you should see output that looks a little like this:
And that’s it, Selenium is now installed and ready to use. One last step before we can have some fun writing our Selenium Python test. We need to set up our driver.
Drivers are required to allow Selenium WebDriver to initiate and interact with a browser instance. Each browser has its own driver, for example, Chrome has ChromeDriver and Firefox has GeckoDriver. We will be using Google Chrome in this demo so let’s go download the driver.
Note: Make sure you check your browser version and download the right driver for your version.
Once downloaded, unzip the driver and copy to a folder on your system. We will save it in C:\bin.
Ok good, the last step before we can write our tests is to add the driver location to our systems PATH variable.
We’re almost there. We’ve completed the set up, so now we can look at our test!
Nice work so far! 😉 Now comes the fun bit of writing our test. First, we can create a new directory to house our project and then open your IDE and navigate to your project directory. We’ve gone for Visual Studio code in this demo.
Next, we can create a new python file in our project directory. We can just call it first_test.py for now.
And we’re ready to go, well sort of…
Of course, before we go any further, we need something to test. We can use https://docket-test.herokuapp.com/register, a demo website for test automation.
We have a project folder and our test python file, we have an IDE, we have an application, now we need to think about what we’re going to do, so let’s break it down into 3 steps:
- Navigate to our application – We’ll call this the Arrange step.
- Complete the registration form and click the Register button – These are our Actions.
- Validate that our user has been registered – We can Assert the result here.
Great. 3 steps organized into Arrange, Act & Assert steps so we can now write some code for each of these steps.
First off, we need to import Selenium WebDriver into our test so we can make use of its API. To do that just add the following line to the top of your first_test.py file.
import selenium.webdriver as webdriver
After that, we can go ahead and implement our Arrange steps. The Arrange section is all about setting everything up so we can go ahead and complete our actions.
Here we will set the driver instance, maximize the window and navigate to our application.
To set the driver instance we can add the following line below our import statement:
driver = webdriver.Chrome()
This tells Selenium to use the ChromeDriver which we downloaded earlier.
Once our driver instance is set, we can navigate to our webpage using the ‘driver.get’ command, like so:
To finish our Arrange steps off we can maximize the window. Just by adding:
Awesome! So far you should have a python file which looks like this:
Now we can look at inputting some data into our registration form. To do this, though we need to know how to locate each element. Let’s jump to our application in chrome and inspect the elements. Simply right click on the element you want to use and select inspect to open developer tools.
There are many ways to locate elements. For the time being, we will use the ID attribute. Now we can go back to our test and write our Act steps. To input text into a field we need to do two things. First, locate the element, then provide the text we want to input. To find the element we will use ‘driver.find_element_by_id()’ and provide the ID value for the element we want. Then we can use the send_keys() function to supply the text we want to write to the field. For example:
So, let us go ahead and complete the first all four fields. Once completed, you should have something which looks like this:
We’re almost there. We just need to click the Register button. To do that is just as simple but instead of using the send_keys() function as we did previously, we’ll use click() like so:
Good job, we have our test! We can go ahead and run it now via the command line/terminal. Just navigate to the directory where your first_test.py file is saved and run python first_test.py. You will see Chrome open enter the input text into each field and click on the register button. If successful you will see this screen:
Hooray! 🤗 We have a working test. But hang on a minute… A test without any validations is pretty pointless, right? How do we tell if the test has been successful? Well, let’s go ahead and add some assertions.
If we go back to our first_test.py file, we can add our assertions. We’re going to add two. First, we will check that the congratulations message appears on the screen when the user is successfully registered then we can check that the user is redirected to the login page.
In order to validate that the Congratulations message is returned on the screen we can first store the message in a variable, then we can assert that the actual text of the message matches what we expect. To get the text we can use the driver.find_element command like we used earlier followed by .txt, like this:
message = driver.find_element_by_xpath("/html/body/div/div/div/div/form/div").text
This line will retrieve the text from the Congratulations alert which appears on the screen and store it in a variable called ‘message’. We can use that variable to validate the correct wording.
You may have noticed that instead of using driver.find_element_by_id as we did before, we’re using driver.find_element_by_xpath. This is because our congratulations message does not have an ID attribute associated with it, so we must use a different locator to find the element in this instance we are using XPath to locate it.
Once stored, we can run our assertion. One of the reasons Python is so great is that it comes with an inbuild assertion library which makes writing assertions super simple. We just need to declare ‘assert’, like this:
assert message == "Congratulations, you are now registered"
For our final assertion, we will validate that the user is redirected to the login page once registered. Like our message check, we will first grab the URL and store it in a variable, then we will use our assert to compare the value against what we expect to see. To get the URL we can use driver.current_url and then compare against the expected URL.
current_url = driver.current_url assert current_url == "https://docket-test.herokuapp.com/login"
The assert section of your test should look like this
One last line to add. At present when our test completes our browser remains open. We want to ensure that it’s closed when we complete our test so we can add driver.quit to the end of our test.
Awesome, we now have a full test, including some assertions! Go ahead and run it again to see if everything is working. It’s worth noting now that the application we’re using persists users for 15 minutes so we may want to wait a few minutes or change the value in our username and email fields if we want to avoid a ‘user exists’ error.
If no errors are returned, then your command line will look like this:
Errors will appear on the command line too. For example, if the text in the Congratulations message is not as expected you could see something like this
And there you have it, your first Selenium WebDriver test using Python. Congratulations! ✨🐍
Let’s recap on what we did. In this tutorial we’ve discussed why we may want to use Python & Selenium, we’ve installed Python along with Selenium, we’ve set up our driver and we’ve written a web test to input and submit data and assert the results. This is a great start! You’ve built a good foundation but remember, this is just the beginning. If you want to build upon this test there are many things you could look at which we didn’t cover in this test.
Using a framework
A framework will give you a structure to work within, not to mention a whole host of features to help build more scalable and robust tests. They will also give you more options for running your tests like better error handling and reporting. Popular Python frameworks include Pytest & unittest.
Creating Page Objects
Page Object Model is a great way of grouping all your locators per page. It makes tests cleaner and more maintainable. In our tests our locators are written directly in our test which makes them difficult to reuse with other tests.
Removing Hardcoded data
Our test is full of ‘hardcoded’ data. This is not great if you want to run the test with a different set of data. Even our assertions are hardcoded. You could look at storing these values differently. Many frameworks provide features to help manage test data and support data-driven testing.
Virtual Environments are a vital feature of the Python ecosystem. Virtual environments provide a way to avoid conflicting requirements between projects by allowing you to install packages, like Selenium, only for the project which needs it. This is useful if you have multiple projects which require different versions of the same Python package.
The possibilities are endless so go explore and see what you can do – Don’t forget to share what you find in the comments below! 👩💻🙌