Selenium With Python:  The Ultimate Introduction Guide For Beginners

Python is one of the most popular and on-demand programming languages right now. The reason is obvious; it offers plenty of benefits to its users and is considered as an all-rounder. You can create websites using Python by leveraging tools such as Flask, Django, and so on. It is also possible to perform web automation using Selenium. And you can use Python for Data Science and Machine Learning, etc. Its simple syntax and the tons of libraries and packages it provides, make it a favorite among programmers.

Python is incredibly easy to learn. It's open-source, free to use, high-level, interpreted, and has one of the largest developer communities worldwide, who are ready to solve any problem you have.

Now, if you are a software developer, you might have heard of Agile workflows. With the need to perform in-sprint testing for every new feature that is added, it is a popular tool. For applications that are small, it is okay to perform manual testing. However, for applications with complex requirements and tons of dependencies, it’s impossible to perform in-sprint testing continuously. Moreover, most of these tests are repeated, and it’s not wise to perform the same testing again and again, although it’s necessary. This problem can be easily solved by automating testing.

Python has a plethora of in-built frameworks for testing, which allows you to perform debugging and create fast workflows. Python modules such as Selenium, Splinter, and other cross-browser or cross-platform frameworks such as Robot, PyTest, etc. make this task very easy.

One of the most widely used test automation tools in Python is Selenium. It’s open-source and free to use. Selenium with Python is used to carry out automated test cases for browsers or web applications. You can easily use it to simulate tests such as tapping on a button, entering content to the structures, skimming the entire site, etc. 

FREE Course: Introduction to Data Analytics

Mastery to Data Analytics Basics is a Click Away!Start Learning
FREE Course: Introduction to Data Analytics

Binding Selenium with Python

The first step for you to start working on Selenium with Python is that you need to write functional test cases using the Selenium web driver. Then, you need to forward a request to the Selenium server that sits at the back-end, which will execute the test cases on the browsers automatically. You can perform tests on any browser including Firefox, Chrome, IE, etc. The only thing that changes are the web drivers, which are specific for each browser.

Binding Selenium with Python is usually via APIs - which you can use to write functional or acceptance test cases with the help of the Selenium web driver. Using this API, you can easily access all the different types of functionalities in an intuitive manner. 

Why Should You Learn Selenium?

There are multiple reasons as to why Selenium is way more popular and powerful when compared to other web-automation tools in the market. Here are the reasons why:

  1. It is an open-source, free-to-use, portable tool that is used to perform web-testing in a seamless manner.
  2. It is a combination of several Domain Specific Language (DSL) and other tools which allow you to perform various types of testing.
  3. It is quite easy to understand, intuitive, and has a low learning curve. The commands are categorized as multiple classes, making them easier to understand.
  4. It takes off a load of the burden from testers, since the amount of time that is required to perform testing, especially on repeated test cases reduces drastically. 
  5. There is a significant reduction in the costs incurred to the business clients, which is a win-win situation.  

How to Install the Package for Using Selenium With Python?

The first step is to install the Selenium package for Python. You can do so using the simple pip command.

$ pip install selenium

PythonAndSelenium_1

You can see how easy it is to install Selenium for Python.

Web Drivers for Using Selenium With Python

Selenium requires a web driver, which will help it interface with the browser that you want to run your tests on. For example, the Firefox browser uses a geckodriver, which you need to install in the right path. The path can be /usr/bin or /usr/local/bin. 

The next step is to install the specific web drivers for the browser on which you want to run the test cases on. Throughout the example, you will be using the Firefox browser to carry out tests.

To install a web driver for the Firefox browser, you can follow these steps.

Assuming that ~/.local/bin is the default path for execution, you can install the geckodriver using the following commands in your Linux machine.

$ wget https://github.com/mozilla/geckodriver/releases/download/v0.29.0/geckodriver-v0.29.0-linux64.tar.gz

PythonAndSelenium_2

$ tar xvfz geckodriver-v0.29.0-linux64.tar.gz

PythonAndSelenium_3

$ mv geckodriver ~/.local/bin

PythonAndSelenium_4

This will download the tar file for the latest version of the geckodriver (v0.29.0) from the official GitHub repository, extract it, and move it to the execution path.

For other browsers, they have their own supported web drivers. Some of them are -

Chrome:

https://sites.google.com/a/chromium.org/chromedriver/downloads

Edge:

https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

Firefox:

https://github.com/mozilla/geckodriver/releases

Safari:

https://webkit.org/blog/6900/webdriver-support-in-safari-10/

Selenium WebDriver Methods

The parent of all the classes and methods that are used for Selenium with Python is the Selenium WebDriver. Using this, you can perform any type of function or operation on any element on a webpage, hence, it is considered as the driving force of Selenium. It has a ton of attributes and methods that are used to aid automation testing in Selenium Python. Some of the most frequently used methods for Selenium WebDriver are - 

Method

Description

add_cookie

This method is used to add cookies to the user’s current session.

back

This method allows you to move one page back.

close

This method will close the current window.

create_web_element

This method will create a web element having a specific element_id.

delete_all_cookies

It will help you delete all the cookies in the current session’s scope.

delete_cookie

It will only delete a single cookie based on the name.

execute_async_script

It will execute JavaScript asynchronously in the current frame.

execute_script

It will execute JavaScript synchronously in the current frame.

forward

It will help you go one page forward.

fullscreen_window

This method will invoke a ‘full screen’ operation specific to the window manager.

get_cookie

It will return a cookie if found, or else none.

get_cookies

It will return a bunch of dictionaries, each corresponding to the cookies that are currently visible in the present session.

get_log

For a log type, you will get all the logs.

get_screenshot_as_base64

You can get a screenshot of the present window as a base64 encoded string.

get_screenshot_as_file

You will get the screenshot of the present window as a binary file.

get_screenshot_as_png

It will save a screenshot of the present window as a PNG file.

get_window_position

You will get the coordinates of the present window.

get_window_rect

You will get the coordinates of the present window along with the width and height.

get_window_size

You will get only the height and width of the present window.

implicitly_wait

You will be able to set a timeout to wait implicitly for an event to occur.

maximize_window

You can maximize the present window that is being used by the web driver.

minimize_window

You will be able to minimize the present window.

quit

You will be able to quit the driver, closing all the associated windows.

refresh

You will be able to refresh the current frame.

set_page_load_timeout

It will allow you to set a time to wait before page loads or else it will throw an error.

set_script_timeout

You will be able to set the time that the script needs to wait during the call of an execute_async_script before yielding an error.

set_window_position

You will be able to set the coordinates of the current window.

set_window_rect

You will be able to set the coordinates of the current window along with the height and width.

current_url

You can get the URL of the web page.

current_window_handle

You can get the handle of the window.

page_source

You will get the current page’s source.

title

It will return the current page’s title.

WebElement Methods for Selenium With Python

The class called selenium.webdriver.remote.webelement.WebElement encloses a plethora of elements within it. These elements can be property, class, tag, or anything. For example, when you find an element in a web page using the driver, you can perform certain actions such as clicking on it or finding the sub-elements. For this, you can leverage several Selenium WebElement methods. Some of the popular Selenium WebElement methods are -

Element Methods

Description

is_selected()

This method returns a boolean value based on whether the element is selected or not.

is_displayed()

This method returns a boolean value based on whether or not the element is displayed.

is_enabled()

This method returns a boolean value based on whether or not the element is enabled.

get_property()

This method can be used to get the properties of a particular element, like text_length property, etc.

get_attribute()

This method can be used to get attributes of a particular element, like getting an href attribute, etc.

send_keys()

This method is used to send a text property to any input field or even an anchor tag or a paragraph.

click()

This method is used to click on any element.

clear()

This method is used to clear the text of any input field.

screenshot_as_png()

This method is used to take a screenshot of the current element.

submit()

This method is used to submit a form.

value_of_css_property()

This method is used to get the value of a specific element’s CSS property.

location

This method is used to get the location of the elements.

screenshot()

This method is used to take the screenshot in the form of binary data.

parent

This method is used to get the parent of the current element.

size

This method is used to receive the size of the current element.

tag_name

This method is used to get the tag name.

text

This method is used to get the text.

rect

This method is used to get a dictionary containing the location and size of the element.

screenshot_as_base64

This method is used to take the screenshot as a base64 encoded string.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

Creating Test Scripts in Selenium with Python

Let’s try to create a simple script for Selenium with Python, which will enable you to explore the free courses in Simplilearn. 

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

You will import the webdriver and keys from the selenium module first.

driver = webdriver.Firefox()

driver.get("https://www.simplilearn.com")

Next, you have to define the webdriver for firefox, and then using the get method on the driver, it will navigate to the Simplilearn website.

Now, let’s go to the website once.

Here, there is a “Free Courses” button where you can find all the free courses in Simplilearn. Hence, you need to get the identifier for the element. Here, you will use the inspect element to do so.

PythonAndSelenium_5

You can see that the title for this is “Free Courses”.

driver.find_element_by_xpath("//a[@title='Free Courses']").click()

driver.quit()

Here, you have used the find_element_by_xpath to get the Free Courses element by title, and then, using the click method on this element, you have clicked the button. Finally, you have to quit the driver.

Let’s try to run the entire program.

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()

driver.get("https://www.simplilearn.com")

driver.find_element_by_xpath("//a[@title='Free Courses']").click()

driver.quit()

PythonAndSelenium_6.
PythonAndSelenium_7

You will see that on program execution, the driver will automatically perform the simulation for you and you will end up on the Free Courses page in Simplilearn.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Wrapping Up!

To sum up, in this article, you looked into how you can leverage Selenium with Python to automate test cases and perform automation of web browsers and web applications. Selenium is an open-source and powerful tool with a vast community, and using it with Python is just a cherry on the top because Python is far less verbose and easy-to-work-with compared to any other programming language.

If you are looking to master the fundamentals of Python and getting a practical understanding of the language, Simplilearn’s Python Certification Course should be the next thing you should learn. It covers all that you need to have a work-ready practical expertise in Python  - data operations, shell scripting, conditional statements and Django to name. Explore this comprehensive program today.

We certainly hope that this article has helped you gain a better understanding of Selenium with Python. Do you have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.