How to use Selenium with Python?

10    Asked by jesse_7843 in QA Testing , Asked on Jan 15, 2025

How do I set up Selenium to work with Python? I just want to write/export scripts in Python, and then run them. Are there any resources for that? I tried googling, but the stuff I found was either referring to an outdated version of Selenium (RC), or an outdated version of Python.

Answered by Michael Robinson

To set up and use Selenium with Python for automation, follow these steps:


Step 1: Install Python

  • Download and install Python from python.org. Ensure you download the latest version.
  • During installation, check the box to "Add Python to PATH."

Step 2: Install Selenium

Use pip to install the Selenium library:

  pip install selenium

Step 3: Download the Appropriate WebDriver

1. Determine your browser version:

  • For Chrome: Open chrome://settings/help to see the version.
  • For Firefox: Go to Help > About Firefox.
  • For Edge: Navigate to Settings > About Microsoft Edge.

2. Download the WebDriver:

  • Chrome: Download ChromeDriver
  • Firefox: Download GeckoDriver
  • Edge: Download EdgeDriver

3.  Extract and Add WebDriver to PATH:

Place the WebDriver executable in a directory included in your system's PATH, or provide its location in the script.

Step 4: Write a Python Script

Here’s a simple example to open a website, interact with it, and close the browser:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
# Set up the WebDriver
driver = webdriver.Chrome(executable_path="path/to/chromedriver") # Replace with your WebDriver path
# Open a website
driver.get("https://www.google.com")
# Interact with the page
search_box = driver.find_element(By.NAME, "q") # Locate the search bar
search_box.send_keys("Selenium Python") # Type the search query
search_box.send_keys(Keys.RETURN) # Press Enter
# Wait for a few seconds to see the results
driver.implicitly_wait(5)
# Close the browser
driver.quit()

Step 5: Run the Script

  • Save the Python script (e.g., selenium_test.py).

Run the script in a terminal or command prompt:

  python selenium_test.py

Step 6: Learn Selenium for Python

  • Official Documentation: Selenium with Python
  • Tutorials and Resources:

Real Python Selenium Guide

FreeCodeCamp Selenium Tutorial

Key Tips

Use webdriver-manager to avoid manual WebDriver downloads:

  pip install webdriver-manager

Example usage:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://www.google.com")
driver.quit()

  • Keep Selenium and WebDriver updated to avoid compatibility issues.
  • Use time.sleep() or explicit waits for handling dynamic content.



Your Answer

Interviews

Parent Categories