Learning Selenium Testing Tools With Python Sample Chapter
Learning Selenium Testing Tools With Python Sample Chapter
$ 44.99 US
27.99 UK
P U B L I S H I N G
Unmesh Gundecha
ee
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Sa
m
Unmesh Gundecha
Selenium IDE: This is a Firefox add-in used to record and play back the
Selenium scripts with Firefox. It provides a graphical user interface to record
user actions using Firefox. It is a great tool to start learning and using Selenium,
but it can only be used with Firefox and other browsers are not supported.
However, it can convert the recorded scripts into various programming languages
supported by Selenium WebDriver, which supports running scripts on browsers
other than Firefox.
Selenium standalone server: This is also known as Selenium Grid and allows
remote and distributed execution of Selenium scripts created with WebDriver.
We can also use the grid feature of the standalone server to run tests in parallel,
including tests on mobile platforms such as Android or Apple iOS for iPhone
and iPad.
As the title suggests, this book will introduce you to the Selenium WebDriver client
library for Python. You will learn how to use Selenium WebDriver in Python to automate
browsers for testing web applications. This book contains lessons right from setting up
Selenium to using the basic and advanced features of Selenium to create and run
automated scripts for testing web applications. This book assumes you have a basic idea
of programming using Python.
Chapter 7, Testing on Mobile, shows you how to test applications on mobile devices
using Selenium WebDriver and Appium. We will set up Appium to test our sample
application on iOS and on an Android emulator and device. You will also learn how to
run native mobile applications using Appium.
Chapter 8, Page Objects and Data-driven Testing, introduces you to two important
design patterns to implement a maintainable and efficient testing framework. You will
learn how to use page objects to hide the technical details of locators, and divide
operations on pages into separate classes and create test cases that are more readable
and easy to maintain. You will then learn how to create data-driven tests using the
unittest library.
Chapter 9, Advanced Techniques of Selenium WebDriver, dives into some of the
advanced techniques of using Selenium for automating browsers for testing. You will
learn how to use various action methods for simulating complex mouse and keyboard
operations using Selenium. You will see how to handle session cookies, capture
screenshots during a test run, and create a movie of the entire test run.
Chapter 10, Integration with Other Tools and Frameworks, shows you how to use
Selenium WebDriver with automated acceptance testing frameworks such as Behave and
Continuous Integration tools. You will first learn how to integrate Selenium with Behave
to create automated acceptance tests. We will implement a sample feature and acceptance
tests on UI using the Selenium WebDriver. At end of the chapter, we will set up running
the tests that we created as part of Continuous Integration using Jenkins. We will set up a
schedule to run the tests on a daily frequency.
By the end of this book, you will have learned all the essential features of Selenium
WebDriver to create your own web testing framework in Python.
Installing Python
You will find Python installed by default on most Linux distributions, Mac OS X, and
other Unix machines. On Windows, you will need to install it separately. Installers
for different platforms can be found at http://python.org/download/.
All the examples in this book are written and
tested on Python 2.7 and Python 3.0 on Windows 8
operating systems.
This is a fairly simple process. This command will set up the Selenium WebDriver
client library on your machine with all modules and classes that we will need to
create automated scripts using Python. The pip tool will download the latest version
of the Selenium package and install it on your machine. The optional U flag will
upgrade the existing version of the installed package to the latest version.
[8]
Chapter 1
You can also download the latest version of the Selenium package source from
https://pypi.python.org/pypi/selenium. Just click on the Download button on
the upper-right-hand side of the page, unarchive the downloaded file, and install it
with following command:
python setup.py install
[9]
Selecting an IDE
Now that we have Python and Selenium WebDriver set up, we will need an editor
or an Integrated Development Environment (IDE) to write automation scripts.
A good editor or IDE increases the productivity and helps in doing a lot of other
things that make the coding experience simple and easy. While we can write Python
code in simple editors such as Emacs, Vim, or Notepad, using an IDE will make life
a lot easier. There are many IDEs to choose from. Generally, an IDE provides the
following features to accelerate your development and coding time:
Syntax highlighting
Project management
Code templates
If you're new to Python, or you're a tester working for the first time in Python, your
development team will help you to set up the right IDE.
However, if you're starting with Python for the first time and don't know which IDE
to select, here are a few choices that you might want to consider.
PyCharm
PyCharm is developed by JetBrains, a leading vendor of professional development
tools and IDEs such as IntelliJ IDEA, RubyMine, PhpStorm, and TeamCity.
PyCharm is a polished, powerful, and versatile IDE that works pretty well. It brings
best of the JetBrains experience in building powerful IDEs with lots of other features
for a highly productive experience.
[ 10 ]
Chapter 1
PyCharm is supported on Windows, Linux, and Mac. To know more about PyCharm
and its features visit http://www.jetbrains.com/pycharm/.
PyCharm comes in two versionsa community edition and a professional edition.
The community edition is free, whereas you have to pay for the professional edition.
Here is the PyCharm community edition running a sample Selenium script in the
following screenshot:
[ 11 ]
The community edition is great for building and running Selenium scripts with its
fantastic debugging support. We will use PyCharm in the rest of this book. Later in
this chapter, we will set up PyCharm and create our first Selenium script.
All the examples in this book are built using PyCharm; however,
you can easily use these examples in your choice of editor or IDE.
[ 12 ]
Chapter 1
Here's the Eclipse PyDev plugin running a sample Selenium script as shown in the
following screenshot:
PyScripter
For the Windows users, PyScripter can also be a great choice. It is open source,
lightweight, and provides all the features that modern IDEs offer such as IntelliSense
and code completion, testing, and debugging support. You can find more about
PyScripter along with its download information at https://code.google.com/p/
pyscripter/.
[ 13 ]
[ 14 ]
Chapter 1
Setting up PyCharm
Now that we have seen IDE choices, let's set up PyCharm. All examples in this book
are created with PyCharm. However, you can set up any other IDE of your choice
and use examples as they are. We will set up PyCharm with following steps to get
started with Selenium Python:
1. Download and install the PyCharm Community Edition from JetBrains site
http://www.jetbrains.com/pycharm/download/index.html.
2. Launch the PyCharm Community Edition. Click on the Create New Project
option on the PyCharm Community Edition dialog box as shown in the
following screenshot:
[ 15 ]
3. On the Create New Project dialog box, as shown in next screenshot, specify
the name of your project in the Project name field. In this example, setests
is used as the project name. We need to configure the interpreter for the
button to set up the interpreter, as shown in the
first time. Click on the
following screenshot:
4. On the Python Interpreter dialog box, click on the plus icon. PyCharm will
suggest the installed interpreter similar to the following screenshot. Select the
interpreter from Select Interpreter Path.
[ 16 ]
Chapter 1
6. On the Create New Project dialog box, click on the OK button to create
the project:
[ 17 ]
In this sample script, we will navigate to the demo version of the application, search
for products, and list the names of products from the search result page with the
following steps:
1. Let's use the project that we created earlier while setting up PyCharm. Create
a simple Python script that will use the Selenium WebDriver client library. In
Project Explorer, right-click on setests and navigate to New | Python File
from the pop-up menu:
[ 18 ]
Chapter 1
2. On the New Python file dialog box, enter searchproducts in the Name field
and click on the OK button:
3. PyCharm will add a new tab searchproducts.py in the code editor area.
Copy the following code in the searchproduct.py tab:
from selenium import webdriver
# create a new Firefox session
driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.maximize_window()
# navigate to the application home page
driver.get("http://demo.magentocommerce.com/")
# get the search textbox
search_field = driver.find_element_by_name("q")
search_field.clear()
# enter search keyword and submit
search_field.send_keys("phones")
search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = driver.find_elements_by_xpath("//h2[@class='productname']/a")
# get the number of anchor elements found
print "Found " + str(len(products)) + " products:"
# iterate through each anchor element and print the text that is
# name of the product
for product in products:
print product.text
# close the browser window
driver.quit()
[ 19 ]
4. To run the script, press the Ctrl + Shift + F10 combination in the PyCharm
code window or select Run 'searchproducts' from the Run menu. This will
start the execution and you will see a new Firefox window navigating to
the demo site and the Selenium commands getting executed in the Firefox
window. If all goes well, at the end, the script will close the Firefox window.
The script will print the list of products in the PyCharm console as shown in
the following screenshot:
[ 20 ]
Chapter 1
We can also run this script through the command line with the
following command. Open the command line, then open the
setests directory, and run following command:
python searchproducts.py
We'll spend some time looking into the script that we created just now. We will go
through each statement and understand Selenium WebDriver in brief. There is a lot
to go through in the rest of the book.
The selenium.webdriver module implements the browser driver classes that are
supported by Selenium, including Firefox, Chrome, Internet Explorer, Safari, and
various other browsers, and RemoteWebDriver to test on browsers that are hosted
on remote machines.
We need to import webdriver from the Selenium package to use the Selenium
WebDriver methods:
from selenium import webdriver
Next, we need an instance of a browser that we want to use. This will provide a
programmatic interface to interact with the browser using the Selenium commands.
In this example, we are using Firefox. We can create
an instance of Firefox as shown in following code:
driver = webdriver.Firefox()
During the run, this will launch a new Firefox window. We also set a few options on
the driver:
driver.implicitly_wait(30)
driver.maximize_window()
[ 21 ]
After loading the page, Selenium will interact with various elements on the page,
like a human user. For example, on the Home page of the application, we need to
enter a search term in a textbox and click on the Search button. These elements are
implemented as HTML input elements and Selenium needs to find these elements to
simulate the user action. Selenium WebDriver provides a number of methods to find
these elements and interact with them to perform operations such as sending values,
clicking buttons, selecting items in dropdowns, and so on. We will see more about
this in Chapter 3, Finding Elements.
In this example, we are finding the Search textbox using the find_element_by_name
method. This will return the first element matching the name attribute specified in
the find method. The HTML elements are defined with tag and attributes. We can
use this information to find an element, by following the given steps:
1. In this example, the Search textbox has the name attribute defined as q and
we can use this attribute as shown in the following code example:
search_field = driver.find_element_by_name("q")
2. Once the Search textbox is found, we will interact with this element by
clearing the previous value (if entered) using the clear() method and
enter the specified new value using the send_keys() method. Next, we
will submit the search request by calling the submit() method:
search_field.clear()
search_field.send_keys("phones")
search_field.submit()
3. After submission of the search request, Firefox will load the result page
returned by the application. The result page has a list of products that
match the search term, which is phones. We can read the list of results and
specifically the names of all the products that are rendered in the anchor
<a> element using the find_elements_by_xpath() method. This will return
more than one matching element as a list:
products =
driver.find_elements_by_xpath("//h2[@class=
'product-name']/a")
4. Next, we will print the number of products (that is the number of anchor <a>
elements) that are found on the page and the names of the products using the
.text property of all the anchor <a> elements:
print "Found " + str(len(products)) + " products:"
for product in products:
print product.text
[ 22 ]
Chapter 1
5. At end of the script, we will close the Firefox browser using the driver.
quit() method:
driver.quit()
This example script gives us a concise example of using Selenium WebDriver and
Python together to create a simple automation script. We are not testing anything in
this script yet. Later in the book, we will extend this simple script into a set of tests
and use various other libraries and features of Python.
Cross-browser support
So far we have built and run our script with Firefox. Selenium has extensive support
for cross-browser testing where you can automate on all the major browsers
including Internet Explorer, Google Chrome, Safari, Opera, and headless browsers
such as PhantomJS. In this section, we will set up and run the script that we created
in the previous section with Internet Explorer and Google Chrome to see the
cross-browser capabilities of Selenium WebDriver.
[ 23 ]
Chapter 1
# get the path of IEDriverServer
dir = os.path.dirname(__file__)
ie_driver_path = dir + "\IEDriverServer.exe"
# create a new Internet Explorer session
driver = webdriver.Ie(ie_driver_path)
driver.implicitly_wait(30)
driver.maximize_window()
# navigate to the application home page
driver.get("http://demo.magentocommerce.com/")
# get the search textbox
search_field = driver.find_element_by_name("q")
search_field.clear()
# enter search keyword and submit
search_field.send_keys("phones")
search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = driver.find_elements_by_xpath("//h2[@class='productname']/a")
# get the number of anchor elements found
print "Found " + str(len(products)) + " products:"
# iterate through each anchor element and print the text that is
# name of the product
for product in products:
print product.text
# close the browser window
driver.quit()
Chapter 1
search_field.send_keys("phones")
search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = driver.find_elements_by_xpath("//h2[@class='productname']/a")
# get the number of anchor elements found
print "Found " + str(len(products)) + " products:"
# iterate through each anchor element and print the text that is
# name of the product
for product in products:
print product.text
# close the browser window
driver.quit()
In this script, we passed the path of the ChromeDriver server while creating
an instance of the Chrome browser class.
4. Run the script. Selenium will first launch the Chromedriver server, which
launches the Chrome browser, and execute the steps. Execution of the actual
steps is very similar to what we observed with Firefox.
Read more about ChromeDriver at https://code.
google.com/p/selenium/wiki/ChromeDriver and
https://sites.google.com/a/chromium.org/
chromedriver/home.
Summary
In this chapter, we introduced you to Selenium and its components. We installed the
selenium package using the pip tool. Then we looked at various Editors and IDEs
to ease our coding experience with Selenium and Python and set up PyCharm. Then
we built a simple script on a sample application covering some of the high-level
concepts of Selenium WebDriver Python client library using Firefox. We ran the script
and analyzed the outcome. Finally, we explored the cross-browser testing support of
Selenium WebDriver by configuring and running the script with Internet Explorer and
Google Chrome.
In next chapter, we will learn how to use the unittest library to create automated
tests using Selenium WebDriver. We will also learn how to create a suite of tests and
run tests in groups.
[ 27 ]
www.PacktPub.com
Stay Connected: