TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Selenium 4 With Python Guide
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python SeleniumPython Tutorials

Selenium 4 With Python Guide

Last updated: May 02, 2024 8:55 pm
By Meenakshi Agarwal
Share
10 Min Read
Selenium 4 With Python Guide
SHARE

Selenium 4 has been around now for quite a bit of time. It came out with many new features, some you can directly use while some will benefit you in the background. This version was released quite a while ago, but not many resources are available telling how to use it with Python. That’s where this tutorial will help you by providing a step-by-step guide to set up Selenium 4 with Python.

Contents
What’s New in Selenium 4Set up Selenium 4 with Python on Ubuntu 22.04Step1. Sync System PackagesStep2. Get the Helper ToolsStep3. Download ChromeDriverStep4. Extract ChromeDriverStep5. Set Env VarsStep6. Install Selenium LibrariesStep7. Verify Selenium VersionTest with a Simple Selenium Python ScriptDemo Script to Search String in GooglePython Script to Demonstrate Selenium 4 Relative LocatorsAdditional NotesSelenium Python Quiz for Automation

Get Started with Selenium 4 Using Python

Python always gives a seamless experience when used with Selenium. With this new release, the integration is going to get better. Let’s quickly learn what’s new inside Selenium 4.

What’s New in Selenium 4

Let’s first quickly go through the list of Selenium 4 features:

  • From an automation testing point of view, the most useful feature is the support for relative locators in Selenium 4. One of the main advantages of this is to ensure that your scripts don’t fail because of a duplicate element. With the help of these relative locators, you can differentiate it from a potential duplicate element. Moreover, you can use this feature to get more reliable test results.
  • With the new version, you can download and install the correct web driver with one line of code. Though, doing it is not as easy as it sounds. 🙂
  • Selenium Grid is more capable now. It can itself register and re-register nodes and has self-healing ability. It can choose a new leader if the main hub fails. The communication between its components is now over HTTPS and it can enforce authentication and authorization for controlling access to resources.
  • The new Selenium now uses built-in Chrome’s headless renderer which speeds up test execution. It shows web pages exactly as they should.
  • Earlier Selenium was using the JSON Wire Protocol, now it has become W3C compliant. For you, it means: You can write tests once and run them everywhere. You can run the same tests in more browsers as your scripts are compatible. Moreover, it ensures the tests are future-ready as any new browser is more likely to use the W3C rules.

Set up Selenium 4 with Python on Ubuntu 22.04

Here’s the step-by-step guide on setting up Selenium 4 on Ubuntu 22.04. The following are the details of the target OS, we will use to set up Selenium:

$ cat /etc/os-release | grep -E '^(NAME|VERSION_ID|VERSION|ID|CODENAME|UBUNTU_CODENAME)'

AME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.3 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
UBUNTU_CODENAME=jammy

Step1. Sync System Packages

Firstly, open the console and take this safe step to sync your installed packages:

$ sudo apt update; apt upgrade

Step2. Get the Helper Tools

Install the helper tools we’ll need during the setup.

$ sudo apt install unzip wget

Step3. Download ChromeDriver

Since we’ll run our tests in the Chrome browser, we need to get the compatible version of its web driver. For this, let’s first check the version of Chrome running on our system:

$ google-chrome --version 
Google Chrome 121.0.6167.160

Now we know the version of our browser. The next thing for you is to get a compatible web driver version. There are two ways to do it. The first one is to follow the below steps to download it manually.

  • Goto this download page: https://googlechromelabs.github.io/chrome-for-testing/ 
  • Choose the compatible version for your Chrome browser.
  • Download the .zip file for Linux.

Another way to install the package is by using the pip command. Check the steps below:

$ pip install chromedriver-py # Install the default version
$ pip install chromedriver-py==121.0.6167.85 # Install a specific version
To set up Selenium with Python, install chrome driver using pip

Step4. Extract ChromeDriver

If you downloaded the web driver file via the link, unzip it and copy its content following the below instructions.

$ sudo unzip chromedriver_linux64.zip -d /opt/chromedriver

Step5. Set Env Vars

Add the path to the chrome driver dir to your system env variables:

echo 'export PATH="/opt/chromedriver:$PATH"' >> ~/.bashrc
source ~/.bashrc

Step6. Install Selenium Libraries

Use pip to install the required Selenium libraries:

$ pip install selenium webdriver-manager

After this check the installation:

$ pip list | grep  selenium
selenium                 4.17.2

Step7. Verify Selenium Version

Open a Python interpreter and try importing the libraries:

import selenium
print(selenium.__version__)

Save the file as “check_version.y”. This should print the installed Selenium version.

$ python3 check_version.py 
4.17.2

Test with a Simple Selenium Python Script

Let’s create a sample Selenium 4 Python script to test your setup:

from selenium import webdriver as wd

dr = wd.Chrome()
dr.get("https://www.google.com")
dr.quit()

Save the script as basic.py and run it:

$ python basic.py

If all goes well, your browser should open and switch to Google.

Demo Script to Search String in Google

Now, let’s do a short exercise to get familiar with Selenium 4 and Python. Prepare a demo script for this purpose. It should open Google search and find a keyword for us.

from selenium import webdriver as dr
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wt
from selenium.webdriver.support import expected_conditions as EC
from chromedriver_py import binary_path as bin

svc = dr.ChromeService(executable_path=bin)
wd = dr.Chrome(service=svc)

# Replace with your desired URL
url = "https://www.google.com/"

# Navigate to the URL
wd.get(url)

# Find the search bar element using its name attr
search_bar = wt(wd, 10).until(
    EC.visibility_of_element_located((By.NAME, "q"))
)

# Type "Selenium test" into the search bar
search_bar.send_keys("Selenium test")

# Find the search button using its name attribute
search_btn = wt(wd, 10).until(
    EC.element_to_be_clickable((By.NAME, "btnK"))
)

# Click the search button
search_btn.click()

# Optional: Wait for a specific element on the next page if needed
# For example, wait for the search results to load
# wt(wd, 10).until(EC.presence_of_element_located((By.ID, "search-results")))

# Print the page title
title = wd.title
print(f"Page title: {title}")

# Close the browser window
wd.quit()

Save the above Selenium 4 Python script as gsearch.py. Run it using the following command. It should search for “Selenium test” and print the page title of the search results page.

$ python3 gsearch.py
Page title: Selenium test - Google Search

Python Script to Demonstrate Selenium 4 Relative Locators

As we know Selenium 4 added new relative locators like above, below, to_right_of, to_left_of, and near, so let’s get to know how to use them with Python.

This example is partially booking a flight from the Google flight page. It finds and fills certain fields on the web page using the relative locators.

from selenium import webdriver as wd
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import *
from time import sleep

# Replace with your desired departure and arrival airports
src_city = "Lucknow"
dstn_city = "Australia"

# Initiate Chrome session
dr = wd.Chrome()

# Navigate to Google Flights
dr.get("https://www.google.com/travel/flights")

# Wait for page to load (adjust timeout if needed)
dr.implicitly_wait(10)

elem_label = dr.find_element(By.XPATH, "//div[text()='Flights']")
print("elem_label = ", elem_label)
print()

# Find search form field below "Flight" label
src = dr.find_element(
    with_tag_name("input").below(elem_label)
)
print("src= ", src)
print()

dstn = dr.find_element(
    with_tag_name("input").to_right_of(src)
)
print("dstn= ", dstn)
print()

# Enter departure and arrival airports
src.clear()
src.send_keys(src_city)
sleep(1)

ele1 = dr.find_element(with_tag_name("div").below(src))
print("ele1= ", ele1)
print()

ele1.click()

dstn.clear()
dstn.send_keys(dstn_city)
sleep(1)

ele2 = dr.find_element(with_tag_name("div").below(dstn))
print("ele2= ", ele2)
print()

ele2.click()

# ... (continue with your booking process)

sleep(5)
dr.quit()

Additional Notes

  • If you set up the Chrome driver manually, then you need to specify its path in your script. However, you won’t need it if you have updated the bashrc file with the driver path.
  • You can use an alternative driver like GeckoDriver (for Firefox) by following similar steps and downloading the respective driver.
  • To set up multiple versions of Selenium, use a tool  virtualenv to create project-specific Python environments and dependencies.

Ethical Considerations

  • Be aware of and respect website terms of service when using automation tools.
  • Avoid actions that might overload servers or violate ethical guidelines.

We hope this becomes your go-to guide to set up Selenium 4 on your Ubuntu system. By the way, don’t leave without attempting the following quiz.

Selenium Python Quiz for Automation

Do a quick self-assessment of your Selenium Python knowledge.

25 QuestionsAttempt
Click to Build a Selenium Python Test Suite

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

TAGGED:Selenium Book a Flightselenium example codeSelenium Testing in Linux
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Selenium 4 Relative Locators Guide Selenium 4 Relative Locators Guide
Next Article Page Object Model and Page Factory Guide in Selenium Java Page Object Model (POM) and Page Factory Guide in Selenium Java

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x