Selenium Python Tutorial – Complete Guide

Welcome to this enlightening journey into the world of Selenium Python. This easy-to-understand, step-by-step tutorial will take you from a beginner to an adept Selenium Python coder in no time.

With an array of examples centered around game mechanics and analogies, you’ll find your learning experience engaging from the get-go.

Why Selenium Python?

Selenium Python is a robust web testing library for the Python programming language. Using Selenium Python, you can automate a variety of tasks on web browsers, making it a handy tool in any developer’s toolkit.

With Selenium Python, you can automate and test web applications, manage cookies, extract and navigate through webpages with mouse and keyboard actions, and much more!

Learning Selenium Python opens a gateway to a variety of career paths, such as web development and QA engineering. It is also an invaluable skill when it comes to debugging, web scraping, and user interaction simulation. Let’s dive into coding!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Coding with Selenium Python – Part 1

We’ll start with the basics of setting up Selenium with Python and writing a simple script to automate web actions.

# Importing WebDriver from selenium
from selenium import webdriver

# Setting up WebDriver for Chrome
driver = webdriver.Chrome()

# Opening a webpage using get() function
driver.get('https://www.google.com')

# Making the browser sleep for 5 seconds
import time
time.sleep(5)

# Closing the browser
driver.quit()

This code will open www.google.com in a new browser window, wait for 5 seconds, and then close the browser. It’s a simple exercise but lays foundation for what is to come.

Coding with Selenium Python – Part 2

Here, we’ll delve into more complex functions that Selenium Python offers.

# Navigating through a website
driver.get('https://www.website.com')
driver.find_element_by_link_text('A Specific Page').click();

This piece of code will open a website, find & click on a link titled ‘A Specific Page’. The browser will then navigate to the corresponding page.

Coding with Selenium Python – Part 3

Let’s continue with further examples and explore how we can interact with forms on a web page using Selenium Python.

# Filling out forms
driver.get('https://www.website.com/form')
element = driver.find_element_by_name('input-field')
element.send_keys('Hello, Zenva!')

This code snippet accesses a web page with a form, finds an input field by its name, and sends a text string to fill out that input field.

# Submitting forms
submit_button = driver.find_element_by_name('submit')
submit_button.click()

After filling out the form, the code identifies the ‘submit’ button and clicks it, thereby sending the form information to the server.

Working with JavaScript alerts in Selenium Python is equally simple. Here’s how:

# Interacting with JavaScript Alerts
from selenium.webdriver.common.alert import Alert
driver.get('https://www.website.com/alert')
Alert(driver).accept()

We navigated to a page with an alert, and using Selenium’s Alert function, we can simply accept the alert.

Coding with Selenium Python – Part 4

Now, let’s consider more complex interactions like handling drop-down menus and checkboxes.

# Dealing with drop-down menus
from selenium.webdriver.support.ui import Select
driver.get('https://www.website.com/form')
select = Select(driver.find_element_by_name('dropdown-menu'))
select.select_by_visible_text('Option 1')

Here, we’ve imported the Select class from Selenium. We find the dropdown menu we want to interact with and choose an option from it by its visible text. Note that other selection methods are also available.

# Checkbox interactions 
checkbox = driver.find_element_by_name('checkbox')
checkbox.click()

This code demonstrates how to interact with checkboxes. We find the checkbox using its name and then click it to check it.

Finally, let’s explore how to fetch cookies for a specific site using Selenium Python.

# Fetching cookies
driver.get('https://www.website.com')
cookies = driver.get_cookies()
print(cookies)

The above code fetches the cookies for our chosen website and prints them out. Unsurprisingly, this can be very useful for testing and debugging.

Coding with Selenium Python – Advanced Interactions

Learning how to handle advanced interactions such as drag and drop, frame switching and explicit wait can make a huge difference in your Selenium Python scripting process. Let’s dive into these concepts one by one.

Drag and Drop

You might come across several scenarios where you are required to perform ‘drag and drop’ operations. Selenium Python makes this task quite simple. Let’s see how:

# Using ActionChains for Drag and Drop
from selenium.webdriver import ActionChains

source = driver.find_element_by_name('source')
target = driver.find_element_by_name('target')

actions = ActionChains(driver)
actions.drag_and_drop(source, target).perform()

In the above code, we started with locating the ‘source’ element (the element which we want to drag) and the ‘target’ element (the element on which we want to drop the source element). We then used ‘ActionChains’ to perform the drag and drop operation.

Frame Switching

Web applications often use frames or iframes to embed an external application or a document within their own application. Selenium Python provides various methods to handle such frames. Let’s see how:

# Switching to a frame by name
driver.switch_to.frame("frameName")

In this example, we switched focus to a frame by its name. Similarly, you can easily switch back to the main content or parent frame:

# Switching back to the main content
driver.switch_to.default_content()

# Switching to the parent frame
driver.switch_to.parent_frame()

Working with Pop-up Windows

It’s quite common for web applications to open up new windows as a result of some user action. Selenium Python allows you to handle these pop-up windows with relative ease:

# Switching to a pop-up window
driver.switch_to.window(driver.window_handles[-1])

# Switching back to the main window
driver.switch_to.window(driver.window_handles[0])

Here, window_handles[-1] points to the most recently opened window, while window_handles[0] refers to the original browser window.

Explicit Wait

Selenium Python provides you with explicit wait functionality. It instructs the execution to wait until a particular condition occurs before proceeding with the next statement:

# Using explicit wait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))

In the above example, Selenium Python will wait for maximum 10 seconds for an element matching the specified ID to become clickable.

With this tutorial, you should have a good understanding of handling various complex interactions in Selenium Python. Practice these concepts as they will come in handy while working on real-world projects.

Where to Go Next with Selenium Python and How to Keep Learning

You’ve now learned to use Selenium Python to automate many types of tasks and interactions on web browsers. While we’ve covered some noteworthy functionalities, exploring further can open up many more possibilities. We at Zenva Academy encourage you to continue exploring, developing, and mastering these skills.

Our Python Mini-Degree at Zenva Academy is a comprehensive collection of courses designed to take you from beginner to advanced Python knowledge. This program is tailored to serve all levels of programmers proficiently.

Providing a depth of knowledge in coding basics, algorithms, object-oriented programming, game and app development, you will find yourself composing a solid foundation in Python. In addition, the Mini-Degree offers you fundamentals to strengthen your learning muscle in Python.

One of the best things about learning with us? You’ll gain strong hands-on experience by working on step-by-step projects, ultimately building a portfolio of Python projects that showcase your skills and competencies to potential employers.

Our courses are structured with flexibility in mind and are accessible around the clock, ensuring learners can fit them into their schedules seamlessly.

For an even wider range of resources, we also offer a broad collection of Python courses, available here. These courses are curated for beginners, intermediate learners and experts – ensuring there’s always something new to learn for everyone.

Conclusion

We hope this guide on Selenium Python has been enlightening and has sparked an increased enthusiasm for web automation and testing. Our journey into Selenium Python and its potential applications just showcases how the world of coding and automated testing can open up a world of opportunities for you.

Take this newfound knowledge and continue your journey. Whether you’re looking to upskill or switch careers, Selenium Python has a lot to offer. We invite you to join us at Zenva Academy in elevating your skills in programming and game development to a whole new level. Happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.