Python Selenium Shell for Debugging and Developement

June 19, 2018, 5:40 a.m.


This is the second blog I'm writing around my experience with putting together a test suite utilizing Python and Selenium. One of the biggest things I missed from using Webdriver.io (a javascript framework for writing integration test) was a shell I could use to interact with a browser to test out my ideas without constantly rerunning test. Here is how I accomplished the same feat in python.

There really isn't anything complicated about it. I start a server in the exact same way, create the driver the same way, and load my page objects the same way. At the end of the day, I'm just running a python file - and in interactive mode so I have access to my variables in the shell afterwards. So, what does this look like?

Well, lets create a basic react app using create-react-app

create-react-app test
cd test/
yarn start

Great! Now we have a frontend server we can initialize our selenium driver against running on localhost:3000

So, in the test directory, lets create a virtual environment (as we always do)

python3 -m venv .venv
source .venv/bin/activate  # connect to the virtual environment
pip install chromedriver_binary selenium  # install dependencies

now, put together a python file that looks likes like this

## debug.py ##
import chromedriver_binary  # noqa: F401 (ignore flake8 for this)
from selenium import webdriver

HOST = 'http://localhost:3000/'

# Initialize selenium driver
driver = webdriver.Chrome(executable_path=chromedriver_binary.chromedriver_filename)
driver.implicitly_wait(15)
driver.get(HOST)

def close():
    """Convenience utility to close selenium session and quit terminal at once"""
    driver.close()
    quit()

back at the command line, run the file in interactive mode so the script doesn't end after executing the script, and you enter the shell. It should look something like this.

(.venv) 🐳  {~/Documents/test}$  python -i debug.py 
>>>

Awesome :) Now lets try actually using our shell.. here's a quick example:

>>> driver
<selenium.webdriver.chrome.webdriver.WebDriver (session="f01dc271a5f1644b3b3a252ed549c33b")>
>>> driver.find_element_by_tag_name('h1')
<selenium.webdriver.remote.webelement.WebElement         
(session="f01dc271a5f1644b3b3a252ed549c33b", element="0.9034359149360807-1")>
>>> driver.find_element_by_tag_name('h1').text
'Welcome to React'
>>> close()  # close the chromedriver browser and quit the shell
(.venv) 🐳  {~/Documents/test}$

It's pretty easy to see how using a shell in that manner gives you an instant feedback loop which makes developing integration test much easier. Thats all there is to it and best of luck!

Comment Enter a new comment: