Selenium with Python

Updated: 13 July 2021

Create a virtual environment

python3 -m venv env

Get gekodriver (for FireFox)
https://github.com/mozilla/geckodriver/releases

It needs to be in the PATH (using Ubuntu here)

sudo mv geckodriver /usr/local/bin/geckodriver

Activate the virtual environment

source env/bin/activate

Install Selenium

pip install selenium

The script

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located

#This example requires Selenium WebDriver 3.13 or newer
with webdriver.Firefox() as driver:
    wait = WebDriverWait(driver, 10)
    driver.get("https://google.com/ncr")
    driver.find_element(By.NAME, "q").send_keys("cheese" + Keys.RETURN)
    first_result = wait.until(presence_of_element_located((By.CSS_SELECTOR, "h3")))
    print(first_result.get_attribute("textContent"))

Leave a comment