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 import Service as ChromeService
from import ChromeDriverManager
from import By

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

# Open a website

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

# Close the browser

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.

Related Tutorials

Quiz on Selenium

Q1. What is a web driver in Selenium Python?

Not answered

Q2. Which of the following is not a popular web driver used in Selenium Python?

Not answered

Q3. What is the method used to switch to a different frame in Selenium Python?

Not answered

Q4. What is the method used to take a screenshot in Selenium Python?

Not answered

Q5. What is the method used to clear the text from an input field in Selenium Python?

Not answered
Code copied to clipboard successfully 👍