Selenium Python Example


Selenium Example in Python

This example is our first program using Selenium in Python.

This may be the first program, but you shall learn many things on getting started with Selenium applications using Python.

In this example, you shall learn how to

1. Create a ChromeDriver instance

A driver is a software component that acts as a bridge between the Selenium WebDriver API and the web browser you want to automate. The driver is responsible for establishing a connection with the browser, sending commands, and receiving responses.

2. Open a URL in the Chrome browser

Opening a specific URL in the browser window is a basic action that you need to do when you are automating the testing of web applications.

3. Access element of the webpage

You need access to the elements in the webpage to validate content in the elements, or interact with the elements. And you would be doing a lot of these actions like finding elements, validating them, or interacting with them.

Selenium Program

Now, let us write the program.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Open a website
driver.get('https://pythonexamples.org')

# Find an element by tag name, and print its content
element = driver.find_element(By.TAG_NAME, "h1")
print(element.text)

# Close the browser
driver.quit()

Here's a breakdown of the program.

The import statements and the first Setup chrome driver section sets up the Chrome driver object without having to download the webdriver for Chrome separately and making it avaialibe in the Path. Just write these statements, and forget about the setup for ChromeDriver.

The next thing is Open a website. We used driver.get() method to open a specific URL.

Then we used find_element() method to find an element in the webpage whose tag name is h1. In other words, we are trying to find the first Heading 1 element in the webpage. From the found element, we read the content of the element, and print it to the output.

At the end, we closed the driver using driver.quit() method.