Overview
Web automation is a powerful tool. Devs mainly use it for UI testing, but there are a ton of other applications! In this post, I’ll be showing you how to automate your chrome browser in python using Selenium.
Content
Setup
You can navigate to the selenium page for more information on the API.
For this post, I will be using OSX (if you bug me, I’ll make one for windows and linux).
-
Install pip by opening your terminal and entering
sudo easy_install pip
. -
Install selenium by typing
pip install selenium
in the terminal. -
We also need the chome webdriver to actually connect to chrome and automate it. You can easily install it with homebrew typing
brew install chromedriver
in the terminal.
Plan
- Go to
www.google.com
- Type
GabrielGhe
in the searchbox - Go to
GabrielGhe.github.io
- Type
java
in the searchbox
This is what it should look like at the end.
Code
We can code now that we know what we want to achieve. The gist below does what’s being displayed in the gif above. Run it yourself to see it live in action!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import time
from selenium import webdriver
WAIT_TIME = 3
# Create the webdriver
driver = webdriver.Chrome()
# Open Chrome and go to google.com
driver.get('http://www.google.com/xhtml');
# Wait for 3 seconds so that you can see what's going on
time.sleep(WAIT_TIME)
# Grab the search box and type in 'GabrielGhe'
search_box = driver.find_element_by_name('q')
search_box.send_keys('GabrielGhe')
search_box.submit()
time.sleep(WAIT_TIME)
# go to another url
driver.get('http://gabrielghe.github.io');
time.sleep(WAIT_TIME)
gabrielghe_search_box = driver.find_element_by_id('q')
gabrielghe_search_box.send_keys('java')
time.sleep(WAIT_TIME)
# Quit after 3 seconds
time.sleep(WAIT_TIME)
driver.quit()