Selenium Python Tutorial For Beginners

In this Selenium Python tutorial learn to code and execute Selenium Test Script using Python Programming Language in different web browsers:

Over the past 5 years, Python language has shown exponential growth in the industry mainly because it is simple and easy to learn. Selenium is one of the most widely used open-source automation testing tools.

Now consider combining Selenium with Python and imagine how robust an automation framework can become.

Selenium Python Tutorial For Beginners

Recommended Reading=> Python Selenium 

In this tutorial, we will learn how to install Python, binding Selenium libraries with Python, how to install and configure PyCharm IDE. At the end of this tutorial, you will be able to code and execute a Selenium test script using Python Programming language in different web browsers.

Installation Of Python

Installing Python is fairly simple. Click here and download the latest version. It will give you a .exe file. Install with all default settings.

>>Click here for step by step details on the installation process. 

Install Selenium Libraries With Python

When you install Python, Selenium libraries are not installed by default. But to verify if Selenium libraries are already present in your Python, open command prompt navigate to the path where you have Python installed and type “pip list“. This command will list all the libraries currently available in your Python.

pip list

What Is PIP

PIP stands for Preferred Installer Program. It is the popular package manager that is used to install software packages written in Python. PIP is installed by default along with Python. Now to bind/install all the required Selenium libraries with Python we need to execute a command

pip install Selenium

Once you execute the command, Selenium libraries will be downloaded and installed.

pip install Selenium

Now verify Selenium libraries using the pip list command.

Verify Selenium libraries

Download And Install Python IDE

To write and execute scripts or programs we need IDE. Hence selection of the same becomes very important. PyCharm is one of the most preferred IDE, especially for Python language. To download PyCharm click here and download the community edition which is free and open source.

download PyCharm

[image source]

It will give you a .exe file. Go ahead and install with all default settings.

Configuration Of Selenium In PyCharm

Once the installation is successful, go to the windows search and type PyCharm and you should be seeing PyCharm community edition as shown in the below image. Click on it to open PyCharm.

Pycharm app

Before writing any code we need to first configure Selenium libraries in PyCharm.

There are 2 ways to configure Selenium for a project in PyCharm. These are as follows:

#1) Using the available Packages option in PyCharm.

When you open PyCharm for the first time, you will be navigated to Create New Project window.

Create new project

Click on Create New Project. By default, the name of the project is taken as untitled. Enter an appropriate project name. Click on Create.

Note: You can change the location of the project.

New Project location

Your project will be created successfully. To verify if Selenium libraries are configured, go to File -> Settings. In setting page go to Project – > Project Interpreter.

Verify if Selenium libraries are configured

Under packages you should be seeing Selenium package. If that is missing, Hit on the “+” button on the right corner. Under available packages, search for Selenium and hit Install Package. Now verify if the Selenium package is installed.

Available Packages

after selenium install

#2) Using Inherit from global site-packages option

This method is fairly simple. Go to File-> New Project. While creating a new project select the “Inherit global site-packages” checkbox. After the project is created, navigate to File -> Settings-> Project -> Project Interpreter, you will be able to see the Selenium package installed already.

11.project page

Adding Drivers To PyCharm

To automate any web application we need to have a web browser and to instruct which browser to execute the scripts on, we need drivers for that particular browser. All the web browsers drivers are available here. Open the webpage and navigate to Browsers.

browsers

Click on documentation for the required browsers and select the stable version of the driver.

To download Chrome: Navigate to Chrome documentation and click on ‘Current stable release’ under “All versions available in Downloads” and download the zip file appropriate for your OS.

Example: “Chromedriver_win32.zip” for Windows.

ChromeDriver

To download Firefox: Navigate to Firefox documentation, click on geckodriver releases and scroll down to find the drivers for all the operating systems.

Example: for Windows 64, select geckodriver-v0.26.0-win64.zip.

Firefox download

To download Microsoft Edge: Navigate to Edge documentation. This will directly open the driver page under Downloads. Example: x64 for Windows 64 bit OS

download Microsoft Edge

First Program Using Selenium Python

Now PyCharm is ready to accept and execute Selenium code. Just to be well organized, we will create 2 directories (directory is similar to a folder). We will use one directory to place all test scripts, let’s call it “Main” and the other directory to place all the web browser’s drivers, let’s name it “Driver”.

Right-click on the Project and Create New Directory as shown in the image below:

new directory

Under the Main directory create New Python File. This will create a .py file and opens the editor.

New Python file

pyfile

Now copy the extracted .exe driver, for example, Chromedriver.exe and paste the file in the Drivers directory.

drivers

We are now ready to write our first automation code using Selenium Webdriver with Python.

Let’s first define the steps to be achieved through automation in the below table.

StepActionExpected Result
1Open Chrome browserChrome browser should launch successfully
2Navigate to www.google.comGoogle webpage should be opened
3Maximize the browser windowBrowser window should be maximized
4Enter LinkedIn login in Google text fieldCorrect text should be entered
5Hit Enter Key Search page should show with proper result
6Click on LinkedIn login URLLinkedIn login page should appear
7Enter Username and PasswordUsername and Password should be accepted
8Click on the Login buttonLinkedIn homepage should be displayed
9Verify the title of the pageLinkedIn should be displayed on the console
10Verify the current URL of the pagehttps://www.linkedin.com/feed/ should be displayed on the console
11Close the browserBrowser window should be closed

To achieve the above-mentioned scenario we will use some of the frequently used Selenium Python commands.

Selenium.Webdriver package provides all the Webdriver implementations. So we need to instruct Python to import Webdriver from Selenium. The Keys class allows us to use the keys in the keyboard like ENTER, ALT, etc.

from selenium import Webdriver
from selenium.webdriver.common.keys import Keys

#1) Open Chrome Browser

To open any browser we need to create an instance of that particular browser. In this example let’s create an instance of Chrome Webdriver and also mention the location of Chromedriver.exe. Just a while ago we downloaded and extracted all the browser drivers and placed it in Driver directory in our PyCharm.

Right-click on the Chromedriver.exe and Copy the Absolute Path and paste in the Webdriver command as given below.

Open Chrome Browser

driver = Webdriver.chrome("C:\Users\Admin\PyCharmProjects\SeleniumTest\Drivers\chromedriver.exe")

#2) Navigate to www.google.com

The driver.get method will navigate to a page mentioned by the URL. You need to specify the full URL.

Example: https://www.google.com

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

#3) Maximize the browser window

driver.maximize_window maximizes the browser window

driver.maximize_window()

#4) Enter LinkedIn login in Google text field

To search LinkedIn login, we have to first identify the Google search textbox. Selenium provides various strategies to locate elements on a page.

>> Refer here for more details on Selenium WebDriver locators.

a) Go to the link

b) Right-click on the search textbox and select inspect element.

Googlesearch

c) We have a name field which has a unique value “q”. So we will use the find_element_by_name locator to identify the search textbox.

d) send_keys function will allow us to enter any text. Example: “LinkedIn Login”

e) Go to Pycharm and enter the following command:

driver.find_element_by_name("q").send_keys("LinkedIn Login")

#5) Hit Enter Key

To navigate to the search result page, we have to either click on the Google Search button or hit Enter key on the keyboard. In this example, we will explore how to hit Enter key through commands. Keys.Enter command will help hit the Enter key on the keyboard.

driver.find_element_by_name("q").send_keys(Keys.Enter )

#6) Click on LinkedIn login URL

Once we land to the search result page we have to click on the LinkedIn Login link. We will use find_element_by_partial_link_text to achieve this.

driver.find_element_by_partial_link_text("LinkedIn Login").click()

#7) Enter Username and Password

Both Username and Password fields have unique ID values and use send_keys to enter the fields.

send keys

driver.find_element_by_id("username").send_keys("enter your username") 
driver.find_element_by_id("password").send_keys("enter your password”)

#8) Click on the Login button

Sign-in is the only button available on the page. So we can use the tagname locator to identify. find_element_by_tag_name.

driver.find_element_by_tag_name("button").click()

#9) Verify the title of the page

The driver.title will fetch the title of the page and print command will print the title of the webpage on the console. Make sure to use braces ().

print(driver.title)

#10) Verify the current URL of the page

The driver.current_url will fetch the URL of the page. print will output the current URL on the console.

print(driver.current_url)

#11) Close the browser

Finally, the browser window is closed driver.close.

driver.close()

Complete test script is given below:

from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
Import time
driver = webdriver.Chrome(r"C:\Users\Admin\PycharmProjects\SeleniumTest\Drivers\chromedriver.exe") 
driver.get("https://www.google.com/") 
driver.maximize_window() driver.find_element_by_name("q").send_keys("LinkedIn login") 
driver.find_element_by_name("q").send_keys(Keys.ENTER) 
driver.find_element_by_partial_link_text("LinkedIn Login").click() 
driver.find_element_by_id("username").send_keys("enter your username") 
driver.find_element_by_id("password").send_keys("enter your password”) 
driver.find_element_by_tag_name("button").click() 
time.sleep(5) 
print(driver.title) 
print(driver.current_url) 
driver.close(

Note: # is used to comment on the line.

time.sleep(sec) is used to delay the execution of the next line.

Running The Program

There are multiple ways to execute the program

#1) Run using PyCharm IDE

This is straight forward. Once you complete coding, you can just right click on the editor and hit Run ”Program name” or Ctrl+Shift+F10 shortcut key.

Run ”Program name”

After the execution, the result will be shown in the console below. Now lets us run our sample code and verify the results.

Syntax Error–Unicode Error

After running the code, we are getting the following error in the console.

error in the console

Let’s try to solve the same. The problem is with the path of the Chrome driver. C:\Users\Admin\PyCharmProjects\SeleniumTest\Drivers\chromedriver.exe

\U in C:\Users become a Unicode character and so \U is converted to Unicode escape character and hence making the path invalid. There are 2 ways to solve this.

#A) Add extra backslashes

driver = Webdriver.chrome("C:\\Users\\Admin\\PyCharmProjects\\SeleniumTest\\Drivers\\chromedriver.exe")

#B) Prefix the string with r:

This will make the string to treat as raw string and the Unicode characters won’t be considered

driver = Webdriver.chrome(r"C:\Users\Admin\PyCharmProjects\SeleniumTest\Drivers\Chromedriver.exe")

TypeError: module object is not callable

Execute the code once again. Now we have a different error in the console.

23.error2

The reason is when you write Webdriver. There are 2 options shown chrome (Selenium Webdriver) and Chrome (Selenium.Webdriver.Chrome.Webdriver) as shown below.

chrome option

We should be selecting Chrome (Selenium.Webdriver.Chrome.Webdriver), if you select the former option, you will end up getting the error in the screenshot above.

Now let’s run the script once again. This time it ran successfully and printed the title and current URL of the webpage on the console.

Result_console

Result_web

Note: If you still encounter a problem. Try the following command:

driver = Webdriver.Chrome(executable_path=
"C:\\Users\\Admin\\PyCharmProjects\\SeleniumTest\\Drivers\\chromedriver.exe")

#2) Running the script in different browsers:

To run the same script in any other browser you just need to create the instance of that particular browser instead of Chrome in the above sample code.

Example for Firefox browser: Replace Chrome with Firefox as shown below:

driver = Webdriver.Firefox(executable_path="C:\\Users\\Admin\\PyCharmProjects\\SeleniumTest\\Drivers\\geckodriver.exe")

For Microsoft Edge browser, replace Chrome with Edge as shown below:

driver = Webdriver.Edge(executable_path="C:\\Users\\Admin\\PyCharmProjects\\SeleniumTest\\Drivers\\msedgedriver.exe")

#3) Running the script in the command prompt:

Right-Click on the directory where you have written your code. Example: “Main”, and then copy the absolute path. Open the command prompt and change the directory to the Python directory with command ‘cd’ and right-click. Once the directory is changed, enter Python “program name”.

Python FirstTest.py

It will execute the code and the result will be shown in the command prompt.

result cmd

FAQs About Selenium Python

Q #1) What is Selenium Python used for?

Answer: A large number of programmers have started using Selenium with Python for test automation. Mentioned below are few of the reasons:

  • For web application testing, Selenium is the most widely used automation tool that offers various functions. Those functions are built to meet the requirements of the web application test.
  • Python language is gaining a lot of popularity because it has fewer syntax issues and can be coded with a simple keyword.
  • Selenium sends standard commands of Python to various browsers irrespective of the browser design.
  • Binding of Python and Selenium provides various APIs which help write functional tests.
  • Both Selenium and Python are open source. So anyone can easily download and use it in any environment.

Q #2) How do I open Chrome in Selenium Python?

Answer: Download the Chrome driver from here and extract the .exe file. Specify the full path of the .exe file while creating an instance of Chrome Webdriver.

driver = Webdriver.Chrome("C:\\Users\\Admin\\PyCharmProjects\\SeleniumTest\\Drivers\\Chromedriver.exe")

Q #3) How do I fix Unicode error in Python?

Answer: There are 2 ways to solve this.

a) Either need to add extra backslashes

driver = Webdriver.Chrome("C:\\Users\\Admin\\PyCharmProjects\\SeleniumTest\\Drivers\\Chromedriver.exe")

b) Prefix the string with r. This will make the string to treat as a raw string and the Unicode characters won’t be considered.

driver = Webdriver.Chrome(r"C:\Users\Admin\PyCharmProjects\SeleniumTest\Drivers\Chromedriver.exe")

Q #4) How do I run Firefox in Selenium Python?

Answer: Download the Firefox geckodriver from here and extract the .exe file. Specify the full path of the .exe file while creating an instance of Firefox Webdriver.

driver = Webdriver.Firefox(executable_path="C:\\Users\\Admin\\PyCharmProjects\\SeleniumTest\\Drivers\\geckodriver.exe").
driver.get(“https://www.google.com”)

This will open the google webpage in Firefox browser

Q #5) How do I get Selenium for Python?

Answer: After installing Python, open command prompt and change the directory to the folder where Python is present and execute pip install Selenium. This will add the latest Selenium libraries to Python.

C:\Users\Admin\AppData\Local\Programs\Python\Python38-32>pip install Selenium.

You can find the Selenium libraries under Lib\site-packages folder in Python.

Conclusion

In this tutorial, we have learned the basics required to start writing the script using Selenium Webdriver and Python language. Below mentioned are the essence of this tutorial:

  1. Python and Selenium have proven to be the most popularly used by programmers. Hence there are a lot of support documents available for the same.
  2. Binding of Selenium libraries with Python can just be done by a single command pip install Selenium.
  3. PyCharm is the most widely used IDE, especially for Python language. The Community edition is completely free for use. Furthermore, it has a lot of packages available which will help in writing functional tests and installation is very easy.
  4. We have also learned how to download different browser drivers and add them in test scripts in PyCharm so that we can test our application in the specified browser.
  5. We learned different Selenium commands using which we can easily automate functionalities of web applications.
  6. We also ran the test script on IDE and command prompt.