Selenium WebDriver Recipes in Python The problem solving guide to Selenium WebDriver in Python 1st Edition Zhimin Zhan pdf download
Selenium WebDriver Recipes in Python The problem solving guide to Selenium WebDriver in Python 1st Edition Zhimin Zhan pdf download
https://ebookname.com/product/selenium-webdriver-recipes-in-
python-the-problem-solving-guide-to-selenium-webdriver-in-
python-1st-edition-zhimin-zhan/
https://ebookname.com/product/selenium-design-patterns-and-best-
practices-build-a-powerful-stable-and-automated-test-suite-using-
selenium-webdriver-kovalenko/
https://ebookname.com/product/problem-solving-with-algorithms-
and-data-structures-using-python-second-edition-bradley-n-miller/
https://ebookname.com/product/programming-in-python-3-a-complete-
introduction-to-the-python-language-2nd-edition-summerfield/
https://ebookname.com/product/essentials-of-online-payment-
security-and-fraud-prevention-essentials-series-1st-edition-
david-a-montague/
Recessions Prospects and Developments Prospects and
Developments 1st Edition Nerea M. Pérez
https://ebookname.com/product/recessions-prospects-and-
developments-prospects-and-developments-1st-edition-nerea-m-
perez/
https://ebookname.com/product/the-last-sorcerers-the-path-from-
alchemy-to-the-periodic-table-1st-edition-morris-richard/
https://ebookname.com/product/essentials-of-stem-cell-
biology-1st-edition-r-lanza/
https://ebookname.com/product/nanomedicine-and-the-
cardiovascular-system-1st-edition-ross-j-hunter-editor/
https://ebookname.com/product/the-new-physics-for-the-twenty-
first-century-2rev-ed-edition-gordon-fraser/
Microtexture Determination and Its Applications 2nd
Edition Valerie Randle
https://ebookname.com/product/microtexture-determination-and-its-
applications-2nd-edition-valerie-randle/
Selenium WebDriver Recipes in Python
The problem solving guide to Selenium WebDriver in
Python
Zhimin Zhan
This book is for sale at http://leanpub.com/selenium-recipes-in-python
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean
Publishing process. Lean Publishing is the act of publishing an in-progress ebook using
lightweight tools and many iterations to get reader feedback, pivot until you have the right
book and build traction once you do.
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
Who should read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
How to read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
Recipe test scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
Send me feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Selenium language bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Install Selenium Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Cross browser testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 unittest - Python Unit Testing Framework . . . . . . . . . . . . . . . . . . . 8
1.5 Run recipe scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3. Hyperlink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.1 Start browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.2 Click a link by text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
CONTENTS
4. Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.1 Click a button by text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.2 Click a form button by text . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.3 Submit a form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.4 Click a button by ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.5 Click a button by name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.6 Click a image button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.7 Click a button via JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.8 Assert a button present . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.9 Assert a button enabled or disabled? . . . . . . . . . . . . . . . . . . . . . . . 28
6. Radio button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.1 Select a radio button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.2 Clear radio option selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.3 Assert a radio option is selected . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.4 Iterate radio buttons in a radio group . . . . . . . . . . . . . . . . . . . . . . 34
6.5 Click Nth radio button in a group . . . . . . . . . . . . . . . . . . . . . . . . 34
6.6 Click radio button by the following label . . . . . . . . . . . . . . . . . . . . 35
6.7 Customized Radio buttons - iCheck . . . . . . . . . . . . . . . . . . . . . . . 36
CONTENTS
7. CheckBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.1 Select by name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.2 Uncheck a checkbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.3 Assert a checkbox is checked (or not) . . . . . . . . . . . . . . . . . . . . . . 37
7.4 Customized Checkboxes - iCheck . . . . . . . . . . . . . . . . . . . . . . . . 38
8. Select List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.1 Select an option by text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.2 Select an option by value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.3 Select an option by index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.4 Select an option by iterating all options . . . . . . . . . . . . . . . . . . . . . 40
8.5 Select multiple options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
8.6 Clear one selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
8.7 Clear all selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.8 Assert label or value in a select list . . . . . . . . . . . . . . . . . . . . . . . . 41
8.9 Assert selected option label . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.10 Assert the value of a select list . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.11 Assert multiple selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
10. Assertion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
10.1 Assert page title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
10.2 Assert Page Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
10.3 Assert Page Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
10.4 Assert Label Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
10.5 Assert Span text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
CONTENTS
11. Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
11.1 Testing Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
11.2 Testing IFrame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
11.3 Test multiple iframes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Afterword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Web Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Preface
After observing many failed test automation attempts by using expensive commercial test
automation tools, I am delighted to see that the value of open-source testing frameworks has
finally been recognized. I still remember the day (a rainy day at a Gold Coast hotel in 2011)
when I found out that the Selenium WebDriver was the most wanted testing skill in terms
of the number of job ads on the Australia’s top job-seeking site.
Now Selenium WebDriver is big in the testing world. We all know software giants such
as Facebook and LinkedIn use it, immensely-comprehensive automated UI testing enables
them pushing out releases several times a day¹. However, from my observation, many
software projects, while using Selenium, are not getting much value from test automation,
and certainly nowhere near its potential. A clear sign of this is that the regression testing is
not conducted on a daily basis (if test automation is done well, it will happen naturally).
Among the factors contributing to test automation failures, a key one is that automation
testers lack sufficient knowledge in the test framework. It is quite common to see some
testers or developers get excited when they first create a few simple test cases and see them
run in a browser. However, it doesn’t take long for them to encounter some obstacles: such as
being unable to automate certain operations. If one step cannot be automated, the whole test
case does not work, which is the nature of test automation. Searching solutions online is not
always successful, and posting questions on forums and waiting can be frustrating (usually,
very few people seek professional help from test automation coaches). Not surprisingly,
many projects eventually gave up test automation or just used it for testing a handful of
scenarios.
The motivation of this book is to help motivated testers work better with Selenium. The book
contains over 190 recipes for web application tests with Selenium. If you have read one of
my other books: Practical Web Test Automation², you probably know my style: practical. I
will let the test scripts do most of the talking. These recipe test scripts are ‘live’, as I have
created the target test site and included offline test web pages. With both, you can:
Usually, a ‘recipe’ book is a reference book. Readers can go directly to the part that interests
them. For example, if you are testing a multiple select list and don’t know how, you can look
up in the Table of Contents, then go to the chapter 8. This book supports this style of reading.
If you are new to Selenium WebDriver, I recommend you to try out the recipes from the
front to back. The recipes in the first half of the book are arranged according to their levels of
complexity, I believe readers can get the pattern of testing with Selenium and gain confidence
after going through them.
Send me feedback
I would appreciate your comments, suggestions, reports on errors in the book and the recipe
test scripts. You may submit your feedback on the book’s site.
Zhimin Zhan
Brisbane, Australia
1. Introduction
Selenium is a free and open source library for automated testing web applications. Selenium
was originally created in 2004 by Jason Huggins, it merged with another test framework
WebDriver in 2011 (that’s why is named ‘selenium-webdriver’) led by Simon Stewart at
Google (update: Simon now works at FaceBook). As WebDriver is a W3C standard¹, it gains
support from all major browser vendors, as a result, Selenium WebDriver quickly become
the de facto framework for automated testing web applications.
¹https://www.w3.org/TR/webdriver/
Introduction 2
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
C#:
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
class GoogleSearch
{
static void Main()
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com");
IWebElement query = driver.FindElement(By.Name("q"));
query.SendKeys("Hello Selenium WebDriver!");
Introduction 3
query.Submit();
Console.WriteLine(driver.Title);
}
}
JavaScript:
driver.get('http://www.google.com/ncr');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(webdriver.until.titleIs('webdriver - Google Search'), 1000);
console.log(driver.title);
Ruby:
require "selenium-webdriver"
puts driver.title
Python:
driver = webdriver.Firefox()
driver.get("http://www.google.com")
elem = driver.find_element_by_name("q")
elem.send_keys("Hello WebDriver!")
elem.submit()
print(driver.title)
Introduction 4
Accept all default options except “Add python.exe to Path” for convenience.
For Mac,
brew install python3
²https://www.python.org/downloads
Introduction 5
Now you are ready to run Selenium script. Type in the above python script (google search)
in a text editor such as NotePad and save as “google_search.py”. Run the command below
in a command window.
> py google_search.py
You will see Firefox browser starting up and performing a Google search.
Chrome
To run Selenium tests in Google Chrome, besides the Chrome browser itself, ChromeDriver
needs to be installed.
Installing ChromeDriver is easy: go to ChromeDriver site⁴.
³http://en.wikipedia.org/wiki/Usage_share_of_web_browsers
⁴https://sites.google.com/a/chromium.org/chromedriver/downloads
Introduction 6
Download the one for your target platform, unzip it and put chromedriver executable in
your PATH. To verify the installation, open a command window (terminal for Unix/Mac),
execute command chromedriver, You shall see:
Starting ChromeDriver 80.0.3987.16 (....) on port 9515
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent
access by malicious code.
The test script below opens a site in a new Chrome browser window and closes it one second
later.
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://testwisely.com/demo")
time.sleep(1) # wait 1 second
driver.quit()
For readers who can’t wait to see the test running, below is the command you need to use to
execute a test, which you can download from the book’s site (Python and selenium library
need to be installed first. See instructions towards the end of this chapter).
> python ch01_open_chrome.py
Firefox
Selenium tests requires Gecko Driver⁵ to drive Firefox. The test script below will open a web
site in a new Firefox window.
⁵https://github.com/mozilla/geckodriver/releases/
Introduction 7
Internet Explorer
Selenium requires IEDriverServer to drive IE browser. Its installation process is very similar
to ChromeDriver. IEDriverServer is available at https://www.selenium.dev/downloads⁶.
Choose the right one based on your windows version (32 or 64 bit).
When a tests starts to execute in IE, before navigating the target test site, you will see this
first:
Depending on the version of IE, configurations may be required. Please see IE and IEDri-
verServer Runtime Configuration⁷ for details.
Edge
Edge is Microsoft’s new and default web browser on Windows 10. To drive Edge with
WebDriver, you need download Microsoft WebDriver⁸. After installation, you will find the
executable (MicrosoftWebDriver.exe) under Program Files folder, add it to your PATH.
However, I couldn’t get it working after installing a new version of Microsoft WebDriver.
One workaround is to specify the driver path in test scripts specifically:
⁶https://www.selenium.dev/downloads
⁷https://code.google.com/p/selenium/wiki/InternetExplorerDriver#Required_Configuration
⁸https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Introduction 8
import unittest
from selenium import webdriver
class FooBarTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome()
@classmethod
def tearDownClass(cls):
cls.driver.quit()
def setUp(self):
self.driver.get("http://travel.agileway.net")
def tearDown(self):
self.driver.find_element_by_link_text("Sign off").click()
def test_first_case(self):
self.assertEqual("Agile Travel", self.driver.title)
self.driver.find_element_by_name("username").send_keys("agileway")
# ...
Introduction 9
def test_second_case(self):
self.driver.find_element_by_id("register_link").click()
# ...
self.assertIn("Register", self.driver.find_element_by_tag_name("body").text)
The keywords class, setUpClass, setUp and def test_xxx define the structure of a test
script file.
• class FooBarTestCase(unittest.TestCase):
Test suite name for grouping related test cases.
• setUpClass() and tearDownClass().
Optional test statements run before and after all test cases, typically starting a new
browser window in setupClass and close it in tearDownClass.
• setUp() and tearDown().
Optional test statements run before and after each test case.
• def test_xxx(self):
Individual test cases.
• Assertions
assertEqual() and assertIn are PyUnit’s two assertion methods which are used to
perform checks. More assert methods⁹
You will find more about unittest from its home page¹⁰. However, I honestly don’t think it
is necessary. The parts used for test scripts are not much and quite intuitive. After studying
and trying out some examples, you will be quite comfortable with it.
The most convenient way to run one test case or a test suite is to do it in an IDE, such as
PyCharm.
When you have a large number of test cases, then the most effective way to run
all tests is done by a Continuous Integration process.
You can locate the recipe either by following the chapter or searching by name. There are
over 150 test cases in the recipes test project. Here is the quickest way to find the one you
want in PyCharm.
Select menu ‘Navigation’ → ‘Go to Symbol …’.
A pop up window lists all test cases in the project for your selection. The finding starts as
soon as you type.
Move mouse to a line within a test case (starting def test_xxx)(self):). Right click and
select “Run ‘Unittest test_xxx’” to run this case.
Introduction 11
The below is a screenshot of execution panel when one test case failed,
You can also run all test cases in a test script file by right clicking the file name in the project
pane and select “Run ‘Unittests in test_file.py’”.
Introduction 12
The below is a screenshot of the execution panel when all test cases in a test script file passed,
INTRODUCTORY.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com