Sitemap
Moraneus

Moraneus

Guide to Using Python Selenium

9 min readJun 5, 2024

--

Press enter or click to view image in full size

In the world of web development and automation, Selenium stands out as a powerful tool for controlling web browsers through programs and automating browser tasks. Whether you’re testing web applications, scraping data, or automating repetitive tasks, Selenium can be your go-to solution. This guide will walk you through the installation and usage of Selenium with Python, from basic to advanced examples, and will also explore some alternatives to Selenium.

What is Selenium?

Selenium is an open-source framework used for automating web browsers. It supports multiple programming languages like Python, Java, C#, and Ruby, making it versatile and widely adopted. Selenium allows you to simulate user interactions such as clicking buttons, entering text, and navigating between pages, which is invaluable for tasks like web scraping, automated testing, and routine web operations.

Key Benefits of Selenium

  • Cross-Browser Compatibility: Selenium supports all major browsers, including Chrome, Firefox, Safari, and Edge.
  • Support for Multiple Languages: Write tests in your preferred programming language.
  • Community and Documentation: Extensive community support and comprehensive documentation make it easier to find solutions and examples.
  • Integration with Testing Frameworks: Selenium integrates well with frameworks like pytest, JUnit, and TestNG.

WebDriver: The Bridge to Your Browser

The WebDriver is a crucial component of Selenium that acts as a bridge between your Selenium scripts and the web browser. It provides a programming interface to create and execute test scripts that can interact with web elements just as a human would. Each browser has its own WebDriver (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox).

Key Features of WebDriver

  • Browser Automation: Automate interactions with web elements.
  • Page Navigation: Programmatically navigate between web pages.
  • JavaScript Execution: Execute JavaScript code within the browser.
  • Screenshot Capture: Capture screenshots of web pages.
  • Browser Configuration: Customize browser settings like user agent, proxy, etc.

How to Install Selenium

Before diving into examples, let’s set up Selenium for Python.

  1. Install Python: Ensure Python is installed on your machine. You can download it from python.org.
  2. Install Selenium: Use pip to install Selenium.
pip install selenium

3. Download WebDriver: Selenium requires a WebDriver to interface with the browser. For example, download ChromeDriver if you’re using Google Chrome. You can find it here:

4. Set Up WebDriver: Ensure the WebDriver is accessible via your system PATH.

Note: In some environments using, e.g., webdriver.Chrome() directly without manually downloading and setting up the WebDriver might work if the WebDriver executable is already in the system PATH or if the browser version matches the WebDriver version bundled with Selenium.

Examples

We will provide a glimpse into the power of Selenium. This will merely whet your appetite.

Automating a Simple Browser Task

Let’s start with a simple example: opening a web page and retrieving its title.

import time
from selenium import webdriver

# Set up the WebDriver (assuming Chrome)
driver = webdriver.Chrome()

# Open a web page
driver.get("https://www.example.com")

# Retrieve and print the title of the page
print(driver.title)

# Just for not let the browser immediate closed
time.sleep(5)

# Close the browser
driver.quit()

In this code, we import the webdriver module from Selenium, which provides the interface to interact with web browsers. We create a WebDriver instance for Chrome, which opens a new Chrome browser window. Using the get method, we navigate to the specified URL ("https://www.example.com"). We access the title property of the WebDriver to get the title of the current page and print it. Finally, after sleeping for 5 seconds, we close the browser using the quit method to end the WebDriver session.

Interacting with Web Elements

Now, let’s interact with web elements like input fields and buttons. We’ll automate a search operation on a website like Google.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

# Set up the WebDriver
driver = webdriver.Chrome()

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

# Find the search box using its name attribute value
search_box = driver.find_element(By.NAME, "q")

# Type 'Selenium Python' in the search box
search_box.send_keys("Selenium Python")

# Simulate pressing the Enter key
search_box.send_keys(Keys.RETURN)

# Wait for a few seconds to see the results
time.sleep(5)

# Close the browser
driver.quit()

In this code, we import necessary modules, including webdriver for browser interaction, By for locating elements, and Keys for keyboard interactions. We use the get method to navigate to Google's homepage ("https://www.google.com"). We use find_element with By.NAME to locate the search box element by its name attribute ("q"). We use the send_keys method to enter the text "Selenium Python" into the search box, followed by pressing the Enter key. We add a delay using time.sleep to wait for the search results to load, then close the browser with quit.

Press enter or click to view image in full size
The search box name is on the right (name=”q”)

Web Scraping

For a more advanced example, we’ll perform web scraping to extract data from a webpage. We’ll scrape the latest news headlines from a news website. Here in this example, we will use a non-existent website.

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Set up the WebDriver
driver = webdriver.Chrome()

# Open the news website
driver.get("https://www.example-news-website.com")

# Allow the page to load
time.sleep(5)

# Find the headlines using their HTML tag and class name
headlines = driver.find_elements(By.CLASS_NAME, "headline-class")

# Extract and print the text of each headline
for headline in headlines:
print(headline.text)

# Close the browser
driver.quit()

In this code, we navigate to the non-existent news website (“https://www.example-news-website.com") using the get method. We add a delay using time.sleep to wait for the page to fully load. We use find_elements with By.CLASS_NAME to locate multiple elements by their class name ("headline-class"). We iterate over the found elements and print their text content using a for loop. Finally, we close the browser using the quit method.

Get Moraneus’s stories in your inbox

Join Medium for free to get updates from this writer.

If you want to test this code on a real website, please modify the website and the By.CLASS_NAME value. Please note that web scraping should be done responsibly and within the terms of service of the website you’re scraping. Additionally, website structures and class names may vary, so you may need to inspect the website’s HTML and adjust the code accordingly.

Changing Browser Settings

We’ll change the user agent and disable images in the browser.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

# Set up Chrome options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
chrome_options.add_argument("--blink-settings=imagesEnabled=false")

# Set up the WebDriver
driver = webdriver.Chrome(options=chrome_options)

# Open a web page
driver.get("https://medium.com/@moraneus")

# Allow the page to load
time.sleep(5)

# Retrieve and print the title of the page
print(driver.title)

# Close the browser
driver.quit()

In this code, we create an instance of Options to customize browser settings. We add arguments to run the browser in headless mode, which means that the browser operates without a graphical user interface. We also change the user agent and disabled images. We pass the chrome_options to the WebDriver to apply these settings. Using the get method, we navigate to the specified URL ("https://medium.com/@moraneus"). We access the title property of the WebDriver to get the page title and print it. Finally, we close the browser using the quit method.

If you want to observe the web browser’s behavior with its graphical interface, without rendering images, you can remove the headless option.

Automating Login

We’ll automate logging into a website.

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Set up the WebDriver
driver = webdriver.Chrome()

# Open the login page
driver.get("https://practicetestautomation.com/practice-test-login/")

# Find and fill the username field
username_field = driver.find_element(By.NAME, "username")
username_field.send_keys("student")

# Find and fill the password field
password_field = driver.find_element(By.NAME, "password")
password_field.send_keys("Password123")

# Find and click the login button
login_button = driver.find_element(By.ID, "submit")
login_button.click()

# Wait for a few seconds to ensure login is successful
time.sleep(5)

# Close the browser
driver.quit()

In this code, we navigate to the login page (“https://practicetestautomation.com/practice-test-login/") using the get method. We use find_element with By.NAME to locate the username field and enter the username using send_keys. We locate the password field and enter the password using send_keys. We locate the submit button and click it using the click method. We add a delay using time.sleep to wait for the login process to complete, then close the browser with quit.

Handling Alerts

We’ll handle JavaScript alerts on a web page.

from selenium import webdriver
from selenium.webdriver.common.by import By

import time


# Set up the WebDriver
driver = webdriver.Chrome()

# Open a web page that triggers an alert
driver.get("https://demo.automationtesting.in/Alerts.html")

# Press on the button that activate the alert
alert_activation_btn = driver.find_element(By.CLASS_NAME, "btn-danger")
alert_activation_btn.click()

# Wait for the alert to appear
time.sleep(3)

# Switch to the alert and accept it
alert = driver.switch_to.alert
alert.accept()

# Let you see that the alert is pressed
time.sleep(3)

# Close the browser
driver.quit()

In this code, we navigate to a page (“https://demo.automationtesting.in/Alerts.html") that triggers a JavaScript alert using the get method. We then click the button that is responsible for the alert to appear. We introduce a delay using time.sleep to allow the alert to show up. We switch to the alert using switch_to.alert and accept it using the accept method. Finally, we close the browser using the quit method.

Taking Screenshots

We’ll capture a screenshot of a web page.

from selenium import webdriver

# Set up the WebDriver
driver = webdriver.Chrome()

# Open a web page
driver.get("https://www.example.com")

# Capture screenshot and save it to a file
driver.save_screenshot("screenshot.png")

# Close the browser
driver.quit()

In this code, we navigate to the specified URL (“https://www.example.com") using the get method. We use the save_screenshot method to capture the screenshot and save it to a file named "screenshot.png". Finally, we close the browser using the quit method.

Press enter or click to view image in full size
The screenshot

Executing JavaScript

We’ll execute a custom JavaScript code on a web page.

from selenium import webdriver
import time

# Set up the WebDriver (assuming Chrome)
driver = webdriver.Chrome()

# Open a web page
driver.get("https://www.example.com")

# Execute custom JavaScript code to create an alert
driver.execute_script("alert('This is a test alert!');")

# Wait for the alert to appear
time.sleep(2)

# Switch to the alert
alert = driver.switch_to.alert

# Print the alert text
print("Alert text: ", alert.text)

# Accept the alert
alert.accept()

# Close the browser
driver.quit()

In this code, we navigate to the specified URL (“https://www.example.com") using the get method. We use the execute_script method to run custom JavaScript code that creates an alert with the message "This is a test alert!". After a short delay to allow the alert to appear, we switch to the alert using switch_to.alert. We then print the text of the alert to the console and accept the alert using the accept method to close it. Finally, we close the browser using the quit method to end the WebDriver session.

Using Proxies

We’ll set up a proxy for the browser session.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# Set up Chrome options
chrome_options = Options()
chrome_options.add_argument("--proxy-server=http://my-proxy-server:8080")

# Set up the WebDriver
driver = webdriver.Chrome(options=chrome_options)

# Open a web page
driver.get("https://www.example.com")

# Retrieve and print the title of the page
print(driver.title)

# Close the browser
driver.quit()

In this code, we create an instance of Options to set the proxy server. We add an argument to use the specified proxy server. We pass the chrome_options to the WebDriver to apply these settings. Using the get method, we navigate to the specified URL ("https://www.example.com"). We access the title property of the WebDriver to get the page title and print it. Finally, we close the browser using the quit method.

Alternatives to Selenium

While Selenium is a powerful tool, there are other options available for web automation and scraping:

  • Beautiful Soup: A Python library for pulling data out of HTML and XML files. It is often used in conjunction with requests for web scraping.
  • Puppeteer: A Node.js library that provides a high-level API to control Chrome or Chromium over the DevTools Protocol.
  • Scrapy: An open-source and collaborative web crawling framework for Python, designed for web scraping.
  • Playwright: A Node.js library to automate Chromium, Firefox, and WebKit browsers with a single API.

Conclusion

Selenium is an invaluable tool for automating web tasks, testing web applications, and scraping data from websites. With its wide range of capabilities and support for multiple programming languages, it’s a must-have for developers and testers alike. By following the examples provided, you can start automating browser tasks, interacting with web elements, and scraping web data efficiently. And if Selenium doesn’t meet all your needs, alternatives like Beautiful Soup, Puppeteer, Scrapy, and Playwright are worth exploring.

Your Support Means a Lot! 🙌

If you enjoyed this article and found it valuable, please consider giving it a clap to show your support. Feel free to explore my other articles, where I cover a wide range of topics related to Python programming and others. By following me, you’ll stay updated on my latest content and insights. I look forward to sharing more knowledge and connecting with you through future articles. Until then, keep coding, keep learning, and most importantly, enjoy the journey!

Happy programming!

--