Listen to this blog
Most of the Automation testing projects that people are working on presently are based on Selenium WebDriver coupled with Java. But as one of the leading QA Companies, we have found that combining Selenium WebDriver with Python has benefits of its own. So in this Selenium with Python Tutorial for Beginners, we will be looking at how we can automate testing using Selenium WebDriver with Python. Before we see how to mix Selenium WebDriver with Python in automation testing, let’s understand why we use Selenium WebDriver and Python rather than any other programming language which is prevalent for automation testing.
Why Selenium WebDriver?
Selenium is an open-source UI automation testing tool. It is very rich in features and allows the users to automate user interaction just as if they were interacting with the web page manually. It has great community support, and it is one of the most widely used automation testing tools for testing web pages. Most importantly, it provides great support to work along with most of the testing frameworks out there.
The setup process is a cakewalk, and you will definitely agree with us once you have gone through the blog.
Python has recently become the most popular programming language due to its great support towards the Data Science and Machine Learning communities. Python has become the beginner’s programming language, all thanks to its simple syntax. Most importantly, it has a wide array of libraries that supports almost any field in the world. In addition to that, Python developer’s community is very active and keeps improving the language with far more frequent updates in comparison to any other programming language in the developing community. So it enables Python to work well with different automation frameworks and tools, making it a stable choice in the testing community as well. Now that we have seen why Python is a really good option, let’s find out how you can install Python on your device and get things started.
We have used a Windows system for this Selenium with Python Tutorial, and if you are also using a Windows system, then you can download the latest version of Python from the official site. But if you are using a Mac, you may find that Python has already been installed. So you can check whether your Mac has Python installed in it by opening your command prompt or terminal and typing “python -V”. If installed, you would see something like this:
Installing Virtual Environment
The best practice for any Python project would be to create a virtual environment and then install all necessary packages within the virtual environment so that the installed packages for one project don’t affect the other. When Python is installed, its standard package manager “pip” also gets installed along with it. So any required packages or libraries can be installed using the below command
pip install <package_name>
We would also be required to install the virtualenv package using the below command,
pip install virtualenv
Visual Studio Code Editor:
In this Selenium with Python Tutorial, we would be using the Visual Studio Code Editor for the sake of easy project management. So you can open the VS code terminal and follow the instructions step by step as shown below:
1. First, change the directory to your desired location
2. Create a project directory
3. Then, change the directory to the created project directory
4. Create a virtual environment
E:\Python_Selenium>python -m venv py_sel
5. Change the directory to the Scripts folder of the virtual environment
6. Activate the created virtual environment
7.Check whether the virtual environment is activated
Now that we have installed the virtual environment, we can go ahead and install Selenium using the pip install selenium command within the created venv. But before that, we have to change the directory to the project directory,
(py_sel) E:\Python_Selenium\py_sel\Scripts>cd..\..\ (py_sel) E:\Python_Selenium>
Now install Selenium,
(py_sel) E:\Python_Selenium>pip install selenium Collecting selenium Using cached selenium-3.141.0-py2.py3-none-any.whl (904 kB) Collecting urllib3 Using cached urllib3-1.26.4-py2.py3-none-any.whl (153 kB) Installing collected packages: urllib3, selenium Successfully installed selenium-3.141.0 urllib3-1.26.4
To check the installed packages, we can use the pip list command.
(py_sel) E:\Python_Selenium>pip list Package Version ---------- ------- pip 21.1.1 selenium 3.141.0 setuptools 49.2.1 urllib3 1.26.4
It’s just that simple, and now Selenium is installed and ready to use. One last step that is left out before we start creating Selenium Python tests is that we need to set up our browser driver.
Drivers are required to allow Selenium WebDrivers to interact and perform actions with a browser instance. So each browser has its own driver just like how Chrome has ChromeDriver, and Firefox has GeckoDriver. We will be using Google Chrome in this Selenium with Python Tutorial, so let’s go download the Chrome Driver.
Make sure you check your browser version and download the appropriate driver version.
Once downloaded, unzip the file and copy the driver to a folder in your system and mention the location in User Variables of the Environment Variables under the Path variable as shown below
We have completed the driver setup and now we can go ahead and write our first automation test.
Selenium with Python Tutorial for writing tests
As we mentioned earlier, for the sake of easy project management we will be using Visual Studio Code Editor for writing automation scripts
We need to open the project directory that we’ve created already for this Selenium with Python Tutorial in VS Code and create a python file within it as we will be writing our automation test script here
In the above image, you can see that the project directory has been opened, and the virtual environment(py_sel) in the terminal is also activated. So it is clear that all the packages that we installed within the venv can now be accessed using the test scripts that we are going to write.
Now we can go ahead and create a python file within the project directory as test.py and write the basic scripts to launch the browser instance and browse to a web page using its URL.
# Importing Selenium web driver in order to use all its functions import selenium.webdriver as webdriver # Set the driver instance drvier = webdriver.Chrome() # Browse to the endpoint driver.get("https://docket-test.herokuapp.com/register") # Maximize the window driver.maximize_window()
So we are now ready to test the functioning of the basic script that is used for launching the browser instance, browsing to the mentioned URL, and maximizing the window.
To run a python file all we need to do is to run the following command
So, it will be python test.py in our case
We can see the browser instance launching, browsing to the mentioned URL, and maximizing the window as we already expected. So let’s go ahead and perform some more actions using some of the rich functions of the Selenium tool.
In this part of the Selenium with Python tutorial, we are going to explore how is it possible to automate a registration and login process that requires data like Username, Email ID, and Password to be provided on the website that we launch. So we will be able to carry this action out by learning to locate web elements like text boxes, buttons, titles, etc., on a webpage.
Locating web elements of a web page is a crucial skill when it comes to automation testing. It is used to automate the actions we would manually perform using a keyboard and mouse while looking at a monitor or display. So the Selenium tool should be informed of the web elements that we need to perform actions on, and we are required to mention each web element uniquely so that it is identified using different locators of the Selenium tool.
Selenium with Python Tutorial for Locating Web Elements
The locators are like an address that uniquely identifies a web element within the web page. Since all the web pages have numerous types of web elements like placeholders, text boxes, radio buttons, etc., identifying these elements requires an accurate and effective approach. As we mentioned earlier, the more effective the locator is, the more stable will the automation script be. We have different types of locators to accurately and precisely locate a web element,
3. Link Text
4. CSS Selector
6. Tag Name
So, now let’s locate the different web elements in the demo web page that we’ve taken, starting with the “Username” placeholder
As we can see, the username placeholder in the DOM (Document Object Model) structure has an ID representing the web element. Since the ID uniquely identifies the “username” web element, we can use it in the Selenium command to locate it and perform actions in it. So in this case, we will be entering a username.
# Enter username in the appropriate placeholder driver.find_element_by_id('username').send_keys('JaneDoe')
Then the next web element is an Email placeholder, we will use a different locator like a name locator to locate the Email placeholder.
# Enter email in the appropriate placeholder driver.find_element_by_name('email').send_keys('[email protected]')
The next web element is the password placeholder which we will identify using the Xpath locator
# Enter password in the appropriate placeholder driver.find_element_by_xpath("//input[@id='password']").send_keys('[email protected]')
The last placeholder is the repeat password placeholder, for which we will identify using the CSS Selector.
# Enter repeat password in the appropriate placeholder driver.find_element_by_css_selector('input#password2').send_keys('[email protected]')
Now that we have located and entered all the required data, the register button is the next web element that has to be located, and it can be done using the ID locator.
But unlike all the earlier four web elements where we needed to perform the action of entering text using the send_keys() function, here we need to perform a click action as it is a radio button. There is no need to worry as Selenium has a unique click() function that we can use to perform the click action as shown below.
# Click register button driver.find_element_by_id('submit').click()
When you are automating any process, it is vital to make sure that there are no mistakes in any of the stages, and this can be achieved by making use of assertions. So what an assertion does is that, it verifies if the result we have obtained is same as the expected result. In this case, we can add an assertion for the confirmation message that is displayed after the successful registration.
# Save the registration success message to a varible for assertion message = driver.find_element_by_xpath("//div[@class='alertalert-info']").text # performing assertion to find the success message is displayed as it should be assert message == 'Congratulations, you are now registered'
What we are doing in the above step is that we are fetching the text of the confirmation message using the XPath locator and the text() function and then storing it in a variable message. After which the inbuilt Python assertion library is used to match and check whether the displayed message is the same as the expected message or not. Since assertion returns a Boolean value (either true or false), the test will pass only if both the actual and expected values match and return as true.
Then the final actions are to be performed in the login form using the created credentials. First, we need to enter “username”, following which the “password” is entered, and finally, we can click on the “Sign In” button
# Enter username in the login page driver.find_element_by_id('username').send_keys('JaneDoe') # Enter password in the login page driver.find_element_by_id('password').send_keys('[email protected]') # Click Sign in button in login page driver.find_element_by_id('submit').click()
Once the “Sign In” button is clicked, we can see that we have logged in successfully by automating the whole process. As our final assertion, we can even check whether we are on the home page or not by using the appropriate URL.
# Get url of the current page current_url = driver.current_url # Perform assertion of the current URL with the expected URL assert current_url == "https://docket-test.herokuapp.com/todo"
The current_url function of the Selenium WebDriver returns the URL of the page which is currently displayed in the browser. We are then asserting that with the expected URL which we know already.
One last line to add in the script for any project is to close the browser, and that process can be automated by an inbuilt function of Selenium WebDriver which is quit()
On the whole, we have written a whole basic automation script in which we have used different types of locators to uniquely identify a web element, which is one of the most important skills in automation. In addition to that, we also included assertions to check whether the actual and expected results were the same. So to sum it all up, these are the basic functionalities required to begin with automation.
We hope you have enjoyed reading this blog, and as the blog title suggests, this is a Selenium with Python Tutorial for beginners. That is why we have covered all the foundations that are needed to start working in automation. Starting from knowing why we use Selenium WebDriver, and especially Python language though there are other prevalent programming languages out there. As a leading QA company providing the best Selenium Testing services, we believe this strong foundation will come in handy for all beginners starting out their journey in automation testing.