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 selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support 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()
driver.maximize_window()
driver.get("https://www.instagram.com/")

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")))
webdriver.ActionChains(driver).move_to_element(login_link).click(login_link).perform()

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")))
webdriver.ActionChains(driver).move_to_element(login_button).click(login_button).perform()

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!