Getting Started with Selenium in Python

I just spent a day doing some browser automation with Selenium in Python, and man-oh-man is it fun! I was surprised at how quickly I was able to get setup and productive, and I thought I’d put together a quick getting started guide to celebrate.

Installation

If you’re starting from scratch (no Python), then the first thing you’ll want to do is install Python. Head on over to python.org and grab a copy. If you install Python 2, you’ll also want to install pip. (Python 3 ships with pip, so it is not necessary to install it yourself.)

With Python and pip, installing Selenium is done with a single command:

pip install selenium

That’s it, now you’re ready to get to automatin’!

Hello World

Open your favorite text editor and create a new file. The first thing you’ll do is import the selenium.webdriver module. Then, you’ll instantiate a webdriver. And then you’ll automate whatever you want!

Here is a script that goes to google and types “hello world” into the box.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com")
driver.find_element_by_id("gbqfq").send_keys("hello world")
driver.close()

Development

I only have one day’s worth of knowledge as I’m writing this, but what I’ve found to work well is to use Chrome’s right-click > Inspect element function for each element that I need to find or interact with and type it into my Python script.

For example, if I wanted to automate entering data into a form, I’d inspect the element to find its id or other identifiable trait (name, css), then type it into my script.

Here’s how you might automate logging into a website:

<form>
    <input id="username" type="text"></input>
    <button id="login-submit" type="submit">Submit</button>
</form>
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("admin")
driver.find_element_by_id("login-submit").click()

And here’s how you might validate that the login was successful:

<div class="banner">
    <span>Welcome, admin</span>
</div>
assert "Welcome, admin" in driver.find_element_by_css_selector("div.banner span").text

Super easy, super fun! Want to learn more? Start here!

Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

One thought on “Getting Started with Selenium in Python”

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: