Lecture 12
Lecture 12
Software Quality
Assurance
Lecture 12
Agenda
• Selenium
• Selenium webdriver
• Selenium IDE
2
WebDriver also enables you to use a programming language in creating your test scripts (not
possible in Selenium IDE).
Following programming languages are supported by WebDriver
● Java
● .Net
● PHP
● Python
● Perl
● Ruby
You do not have to know all of them. You just need to be knowledgeable in one
Selenium Server is written in Java, and you need to have JRE 1.6
or above to install it on your server. It is available on Selenium’s
download page.
How to run your automated test using Selenium and Python?
Once you have completed the pre-requisites section, you are ready
to start your first test in Selenium with the Python programming
language!
1. First import the webdriver and Keys classes from Selenium.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
The webdriver class will connect you to a browser’s instance. The Keys class
lets you emulate the stroke of keyboard keys, including special keys like “Shift”
and “Return”.
2. Next, create an instance of Chrome with the path of the driver that you
downloaded through the websites of the respective browser. In this example,
we assume that the driver is in the same directory as the Python script that you
will execute.
driver = webdriver.Chrome('./chromedriver')
If you are testing on your local machine, this opens an instance of Chrome
locally. This command lets you perform tests on it until you use the .close()
method to end the connection to the browser.
3. Next, use the .get() method of the driver to load a website. You may also load
a local development site as this process is equivalent to opening a window of
Chrome on your local machine, typing a URL and hitting Enter. The .get()
method not only starts loading a website but also waits for it to render completely
before moving on to the next step.
driver.get("https://www.python.org")
4. Once the page loads successfully, you can use the .title attribute to access the
textual title of the webpage. If you wish to check whether the title contains a
particular substring, you can use the assert or if statements. For simplicity, let us
print the title of the page.
print(driver.title)
If you are running the test on a Python interpreter, you notice that the Chrome browser
window is still active. Also, a message on Chrome states that automated software is
controlling it at the moment.
Inspect python.org
5. Next, let us submit a query in the search bar. First, select the element from
the HTML DOM and enter a value into it and submit the form by emulating the
Return key press. You can select the element using its CSS class, ID, its name
attribute, or even the tag name. If you check the source of the query search bar,
you notice that the name attribute of this DOM element is “q”. Therefore, you
can use the .find_element_by_name() method as follows to select the element.
search_bar = driver.find_element_by_name("q")
6. Once the DOM element is selected, you first need to clear its contents using
the .clear() method, enter a string as its value using the .send_keys() method
and finally, emulate the press of the Return key using Keys.RETURN.
search_bar.clear()
search_bar.send_keys("getting started with python")
search_bar.send_keys(Keys.RETURN)
from selenium import webdriver
driver = webdriver.Chrome("C:\Program
Files\Google\Chrome\Application\chromedriver.exe")
driver.get("https://www.python.org")
search_bar = driver.find_element_by_name("q")
search_bar.clear()
search_bar.send_keys(Keys.RETURN)
Using Selenium to write tests
• Selenium is mostly used for writing test cases. The selenium package
itself doesn’t provide a testing tool/framework. You can write test cases
using Python’s unittest module. The other options for a tool/framework
are pytest and nose.
• Here is the modified example which uses unittest module. This is a test
for python.org search functionality:
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
Navigating
The first thing you’ll want to do with WebDriver is navigate to a link. The normal
way to do this is by calling get method:
driver.get("http://www.google.com")
Interacting with the page
To interact with the pages, or, more specifically, the HTML elements within a
page. First of all, we need to find one. WebDriver offers a number of ways to find
elements. For example, given an element defined as:
<input type="text" name="passwd" id="passwd-id" />
you could find it using any of:
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-
id']")
element = driver.find_element_by_css_selector("input#passwd-
id")
First of all, you may want to enter some text into a text field:
element.send_keys("some text")
You can simulate pressing the arrow keys by using the “Keys” class:
1. Locating by Id
Use this when you know the id attribute of an element. With this strategy, the first element with a matching id
attribute will be returned. If no element has a matching id attribute, a NoSuchElementException will be
raised.
<html>
<body>
For instance, consider this page source: <form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
</form>
</body>
</html>
The form element can be located like this:
login_form = driver.find_element_by_id('loginForm')
2. Locating by Name
Use this when you know the name attribute of an element. With this strategy, the first element
with a matching name attribute will be returned. If no element has a matching name attribute, a
NoSuchElementException will be raised.
<html>
For instance, consider this page source: <body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
</html>
The username & password elements can be located like this:
username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')
3. Locating by XPath
• XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of
XML (XHTML), Selenium users can leverage this powerful language to target elements in their web
applications.
• XPath supports the simple methods of locating by id or name attributes and extends them by opening up all
sorts of new possibilities such as locating the third checkbox on the page.
• One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element
you wish to locate.
• You can use XPath to either locate the element in absolute terms (not advised), or relative to an element that
does have an id or name attribute. XPath locators can also be used to specify elements via attributes other than
id and name.
For instance, consider this page source:
<html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="button" value="Clear" />
</form>
</body>
</html>
The form elements can be located like this:
login_form = driver.find_element_by_xpath("/html/body/form[1]")
login_form = driver.find_element_by_xpath("//form[1]")
login_form = driver.find_element_by_xpath("//form[@id='loginForm’]”)
element = driver.find_element_by_xpath("//select[@name='name']")
all_options = element.find_elements_by_tag_name("option")
option.click()
This will find the first “SELECT” element on the page, and cycle through each of its OPTIONs in
turn, printing out their values, and selecting each in turn.
As you can see, this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s support
classes include one called a “Select”, which provides useful methods for interacting with these:
select = Select(driver.find_element_by_name('name'))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)
WebDriver also provides features for deselecting all the selected options:
select = Select(driver.find_element_by_id('id'))
select.deselect_all()
This will deselect all OPTIONs from that particular SELECT on the page.
driver.forward()
driver.back()
Explicit waits in Selenium Python
• When a page is loaded by the browser, the elements within that page
may load at different time intervals.
• This makes locating elements difficult: if an element is not yet present
in the DOM, a locate function will raise an ElementNotVisibleException
exception. Using waits, we can solve this issue.
• Waiting provides some slack between actions performed – mostly
locating an element or any other operation with the element. Selenium
Webdriver provides two types of waits – implicit & explicit.
Explicit Waits
• An explicit wait is a code you define to wait for a certain condition to occur
before proceeding further in the code.
• The extreme case of this is time.sleep(), which sets the condition to an exact
time period to wait.
• There are some convenience methods provided that help you write code that
will wait only as long as required.
• Explicit waits are achieved by using webdriverWait class in combination with
expected_conditions.
Let’s consider an example –
# import necessary classes
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
as EC
● title_is
● title_contains
● presence_of_element_located
● visibility_of_element_located
● visibility_of
● presence_of_all_elements_located
● element_located_to_be_selected
● element_selection_state_to_be
● element_located_selection_state_to_be
● alert_is_present
How to create an Explicit wait in Selenium Python ?
Explicit wait as defined would be the combination of WebDriverWait and Expected conditions. Let’s implement this
on https://www.geeksforgeeks.org/ and wait 10 seconds before locating an element.
# import webdriver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# create webdriver object
driver = webdriver.Firefox()
# get geeksforgeeks.org
driver.get("https://www.geeksforgeeks.org/")
# get url
driver.get("http://somedomain / url_that_delays_loading")
This waits up to 10 seconds before throwing a TimeoutException unless it finds the element to return within
10 seconds.
How to create an Implicit wait in Selenium Python ?
Implicit wait as defined would be the set using implicitly_wait method of driver. Let’s implement this on
https://www.geeksforgeeks.org/ and wait 10 seconds before locating an element.
# import webdriver
from selenium import webdriver
# create webdriver object
driver = webdriver.Firefox()
# get geeksforgeeks.org
driver.get("https://www.geeksforgeeks.org/")
This is useful for doing more complex actions like hover over and drag and
drop. Action chain methods are used by advanced scripts where we need to
drag an element, click an element
How to create an Action Chain Object ?
To create object of Action Chain, import Action chain class from docs and pass driver
as the key argument. After this one can use this object to perform all the operations
of action chains.
# import webdriver
from selenium import webdriver
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav # submenu1")
ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
Or actions can be queued up one by one, then performed.:
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav # submenu1")
actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()
Method Description
click Clicks an element.
click_and_hold Holds down the left mouse button on an element.
context_click Performs a context-click (right click) on an element.
double_click Double-clicks an element.
Holds down the left mouse button on the source element, then moves to
drag_and_drop
the target element and releases the mouse button.
drag_and_drop Holds down the left mouse button on the source element, then moves to
_by_offset the target offset and releases the mouse button.
key_down Sends a key press only, without releasing it.
key_up Releases a modifier key.
move_by_offset Moving the mouse to an offset from current mouse position.
move_to_eleme
Moving the mouse to the middle of an element.
nt
move_to_eleme Move the mouse by an offset of the specified element, Offsets are
nt_with_offset relative to the top-left corner of the element.
perform Performs all stored actions.
pause Pause all inputs for the specified duration in seconds
release Releasing a held mouse button on an element.
reset_actions Clears actions that are already stored locally and on the remote end
send_keys Sends keys to current focused element.
Syntax –
click(on_element=None)
Args –
on_element – The element to click. If None, clicks on current mouse position.
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
Example –
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
Now one can use click_and_hold method as an Action chain as below –
click_and_hold(on_element=element)
How to use double_click Action Chain method in Selenium Python ?
Program –
# import webdriver
from selenium import webdriver
48
Selenium IDE Commands
Each Selenium IDE test step can chiefly be split into the following three
components:
• Command
• Target
• Value
waitForElement Sleeps the execution and waits until the specified element is present 1
Present
chooseOkOnNext Click on ”OK” or “Cancel” button when next confirmation box appears. 0
Confirmation,
chooseCancelOn
NextConfirmation
Commonly used Selenium
IDE commands
assertTitle gets the title of a website and checks it again the provided text.
• Assert and verify commands are both useful for verifying condition
match or not.
• The difference is that verify command will verify the condition and if its
not match, it will give error message in Log area and the macro
continues to run.
• With the assert command, if the condition does not match then it will
stop remaining macro execution in the selenium IDE software testing
tool.
assertText Example
Syntax Description
• tag = the HTML tag of the element being
accessed
css=tag.class • . = the dot sign. This should always be present
when using a CSS Selector with class
• class = the class of the element being accessed
Open http://omayo.blogspot.com/
click at css=input.gsc-search-button 10,20
Locating by Name
Locating elements by name are very similar to locating by ID, except that we use
the “name=” prefix instead.
Target Format: name=name of the element
Locating by Link Text
This type of CSS locator in Selenium applies only to hyperlink texts. We access the link
by prefixing our target with “link=” and then followed by the hyperlink text.
Locating by CSS Selector
CSS Selectors in Selenium are string patterns used to identify an element based on a
combination of HTML tag, id, class, and attributes. Locating by CSS Selectors in
Selenium is more complicated than the previous methods, but it is the most common
locating strategy of advanced Selenium users because it can access even those elements
that have no ID or name.
CSS Selectors in Selenium have many formats, but we will only focus on the most
common ones.
• Tag and ID
• Tag and class
• Tag and attribute
• Tag, class, and attribute
• Inner text
Locating by CSS Selector – Tag and ID
Again, we will use Facebook’s Email text box in this example. As you can remember, it has an ID of
“email,” and we have already accessed it in the “Locating by ID” section. This time, we will use a
Selenium CSS Selector with ID in accessing that very same element.
Syntax Description
Syntax Description
• tag = the HTML tag of the element being accessed
• . = the dot sign. This should always be present
css=tag.class
when using a CSS Selector with class
• class = the class of the element being accessed
Locating by CSS Selector – Tag and Attribute
This strategy uses the HTML tag and a specific attribute of the element to be accessed.
Syntax Description
• tag = the HTML tag of the element being accessed
• [ and ] = square brackets within which a specific attribute
and its corresponding value will be placed
css=tag[attribute=value] • attribute = the attribute to be used. It is advisable to use an
attribute that is unique to the element such as a name or
ID.
• value = the corresponding value of the chosen attribute.
Locating by CSS Selector – tag, class, and attribute
Syntax Description
• tag = the HTML tag of the element being accessed
• . = the dot sign. This should always be present when
using a CSS Selector with class
• class = the class of the element being accessed
Syntax Description
Open http://omayo.blogspot.com/
type name=q SomeText
Open http://omayo.blogspot.com/
click id=checkbox2
click at is one of the commands in Selenium IDE.
The purpose of click at command in Selenium IDE, is to click on any UI element at the given x & y
coordinate position of the UI element.
similarly, uncheck.
assert selected value is one of the commands
in Selenium IDE.
The purpose of assert selected value command
in Selenium IDE, is to check whether the given
option is selected in the dropdown field.
click id=alert1
assert alert Hello
assert confirmation is one of the commands in Selenium IDE.
The purpose of assert confirmation command in Selenium IDE, is to check whether the required confirmation
dialog is displayed on the page.
click id=confirm
assert confirm Press OK to confirm
open http://omayo.blogspot.com/
click id=prompt
assert prompt What is your name?
edit content is one of the commands in Selenium IDE.
The purpose of edit content command in Selenium IDE, is to change the value of the given UI element.
Note: This option only with the UI elements who’s contenteditable attribute value is set to ‘true’ as shown
below:
By default, most of the UI element will have the above attribute ‘contenteditable’ set to
‘false’ and hence this Selenium IDE command will give error on execution.
https://jqueryui.com/droppab
open le/
select frame index=0
mouse down id=draggable
mouse move at id=droppable
mouse up id=droppable
submit is one of the commands in Selenium IDE.
The purpose of the submit command is to submit any form on the page say Login, Signup
forms, etc.
http://tutorialsninja.com/demo/index.p
open hp?route=account/login
submit css=form[action$=’login’]
open http://omayo.blogspot.com/
store QAFox.com x
echo ${x}
After incorporating the commands in the above table, Our Selenium IDE should look like
below:
Run the test and observe that the
test will be passed and the value
stored in the variable ‘x’ will be
printed in the ‘Log’ tag as shown
below:
assert is one of the commands in Selenium IDE.
The purpose of the assert command is to check the value stored in a variable is according to
the expected result
Command Target Value
open http://omayo.blogspot.com/
store title x
The purpose of the wait for element editable command is to wait for the element to get
editable. i.e. If any required element on the application is by default in non-editable state
and gets editable in some time, we can use wait for element editable command to wait
for the element to get editable, before editing the element.
Follow the below steps for practicing wait for element editable command in Selenium IDE
1) Let’s write the below code in Selenium IDE to wait for the ‘checkbox’ option to get
editable after clicking on the ‘Check this’ button:
open http://omayo.blogspot.com/
xpath=//button[text()=’Check
click this’]
open http://omayo.blogspot.com/
echo ${x}
store json is one of the commands in Selenium IDE.
The purpose of the store json command is to retrieve and store json content into a
variable in Selenium IDE.
http://omayo.blogspot.co
open m/
open http://omayo.blogspot.com/
store title x
else is the command in Selenium IDE will be executed when the if condition
results in false.
The purpose of the if command is to check whether the given condition is
true or false. If the condition results in true, the Selenium IDE statements
inside the if block will be executed. If the condition results in false, the
Selenium IDE statements inside the else block will be executed.
The else command will work as depicted below:
1) Let’s create a test in Selenium IDE for retrieving the title of the page, adding if condition to check whether
the retrieved title is equal to the expected title text, else to execute its block when the retrieved title is not equal
to the expected title text and printing the result using the below Selenium IDE code:
else if is the command in Selenium IDE will be executed when the if condition results in
false and we have another condition to be validated before going to the else block.
The purpose of the if command is to check whether the given condition is true or false. If
the condition results in true, the Selenium IDE statements inside the if block will be
executed. If the condition results in false, the if block will be skipped and the next else
if condition will be checked for true or false. If the else if condition is true, the statements
inside the else if block will be executed. And if the else if condition is false, the else if block
will be skipped and the next else if condition or else block will be executed.
The else if command will work as depicted below:
1) Let’s create a test in Selenium IDE for retrieving the title of the page, adding if condition
to check whether the retrieved title is equal to the expected title one text, else if condition to
check whether the retrieved title is equal to the expected title two text, else to execute its
block when the retrieved title is not equal to the expected title one and title two texts and
printing the result using the below Selenium IDE code:
Command Target Value
open http://omayo.blogspot.com/
store title x
if ${x} === “xyz”
echo Correct title one is displayed on the web page
else if ${x} === “omayo (QAFox.com)”
echo Correct title two is displayed on the web page
else
echo Wrong title is displayed on the web page
end
while is one of the commands in Selenium IDE and we can end it with end command.
while is the command in Selenium IDE used for executing a set of same statements
multiple times until the while condition becomes false.
We will execute a set of statements inside the while block multiple times until
the while condition becomes false. i.e. We will execute the same set of statements inside
the while block until the value inside the variable x is smaller than 5. Initially, we will
assign the value 1 to the variable x and thereafter increment the value stored in variable x
by 1 until the while condition becomes false (i.e. when the value of x becomes 5,
the while condition x<5 will become false).
The while command will work as depicted below:
As you can see in the above flow diagram, the block of code inside the while block
will be executed multiple times until the while condition become false.
1) Let’s create a test in Selenium IDE for printing the value stored in the variable x until
the while condition become false as shown below:
open http://omayo.blogspot.com/
while ${x}<5
echo ${x}
end
• do and repeat if are the commands in Selenium IDE, which needs to be used
together.
• do and repeat if are the command in Selenium IDE used for executing a set of same
statements multiple times until the repeat if condition becomes false.
• In while command, the condition to be checked for entering into the iterative loop
block will be at the beginning. Whereas in do command, we will check the condition
at the end of the iterative loop block using repeat if command.
• ________________________________________
while condition
statements inside the while block
end
________________________________________
do
statements inside the do block
repeat if condition
________________________________________
We will execute a set of statements inside the do block multiple times
until the repeat if condition becomes false. i.e. we will execute the same
set of statements inside the do block until the value inside the variable x
is smaller than 5. Initially, we will assign the value 1 to the variable x
and thereafter increment the value stored in variable x by 1 until
the repeat if condition becomes false (i.e. when the value of x becomes
5, the repeat if condition x<5 will become false).
The do command will work as depicted below:
As you can see in the above flow diagram, the block of code inside the do block will
be executed multiple times until the repeat if condition becomes false.
1) Let’s create a test in Selenium IDE for printing the value stored in the variable x until the repeat if condition
of do block become false as shown below:
open http://omayo.blogspot.com/
do
echo ${x}
repeat if ${x}<5
2) Click on ‘Run current test’ option and observe that the test got
successfully executed and the value stored in the variable x will be printed
multiple times under the Log tab.
Note: The initial value stored in the variable x is 1 (i.e. we have executed
JavaScript statement ‘return 1’ as shown above using execute
script command, for storing the value 1 into the variable x)
And also, we have incremented the value stored in the variable x by 1 every
time we enter into the while block. (i.e. we have executed JavaScript
statement ‘return ${x}+1’ as shown above using execute script command,
for incrementing the value stored in the variable by 1 every time we enter to
the do block)
for each is one of the commands in Selenium IDE.
for each is the command in Selenium IDE used for executing a set of same statements
multiple times until all the values in the given array (i.e. multiple set of values stored in a
single variable) are completed.
Command Target Value
open http://omayo.blogspot.com/
echo ${itr}
end