search by tags

for the user

adventures into the land of the command line

selenium and python

A while ago I was asking a friend how to automate UI testing. He told me about something called Selenium which could simulate mouseclicks and typing and other things. For example, you could use it to simulate a user logging in to a website.

“Great!” I though, but how do I do it? Well…

$ pip install selenium

Include a bunch of stuff from selenium.

from selenium import webdriver
from import By
from import WebDriverWait
from import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

“webdriver” is a must. “WebDriverWait” is good for getting your script to pause and wait for something to happen before continuing. “By” is for choosing how you want to select an element. There are many choices, in my example I used CSS selectors. “expected_conditions” is for letting selenium know what context to expect an element on the page to be in. And “Keys” is for simulating typing keys into text fields.

Open a browser like Firefox, maximise the window and navigate somewhere.

driver = webdriver.Firefox()

Wait for the page to finish loading, or for a particular element on the page to be clickable, then click the element.

wait = WebDriverWait(driver, 10)
login_link = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a._k6cv7")))

Enter text into a field, move the mouse to the login button and click it.

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[name='username']"))).send_keys("mygroovyusername")
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[name='password']"))).send_keys(mygroovypassword)
login_button = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button")))

Wait for some loading to complete before continuing.

some_available_link = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a._soakw" )))

So cool!