Professional Documents
Culture Documents
Simona Pitam
Understand Selenium Locators And Master CSS/XPath
What Is XPath?
XPath is a technique for uniquely identifying an element on a web page. It behaves like an address to an HTML
element such as check boxes, text, images, links, and divs, etc. In Selenium, we treat XPath as one of the most
trusted element locators. XPath is much more than an address as it not only points to the end point, it also
2) Relative XPath
The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can
select the element from the root node.
Absolute Xpath: It uses Complete path from the Root Element to the desire element.
Relative Xpath: You can simply start by referencing the element you want and go from there.
Always Relative Xpaths are preferred as they are not the complete paths from the Root element. (//html//body)
Beacuse in future any of the webelement when added/Removed then Absolute Xpath changes.
/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]
and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.
.//*[@id='answers']/h2[1]/a[1]
Simona Pitam
XPATH Allocation in Chrome
Add Chrome Extension
ChroPath
Right Click
Inspect
By xpath - Locates the web element using its XPaths(explained in detailed here Simona Pitam
For locating the web elements to be styled, we use certain rules provided as CSS Selectors.
For example, the following statement first locates a web element satisfying the selector pattern -
"div#searchBox" and then aligns the text inside it to center.
div#searchBox {text-align: center;} Simona Pitam
CSS Locators
In Selenium, we can use these CSS Selector rules/patterns for locating web elements and later
perform different operations on them. For example-
//Locating searchBox element using CSS Selector
WebElement searchBox = driver.findElement(By.cssSelector("div#searchBox"));
Simona Pitam
Using Drop Down Box in Selenium
Explanation of Application under Test
We have designed the web page in a way to include a few fundamental types of web elements.
● Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs
the user to “https://www.google.co.in/” and “http://www.abodeqa.com/” respectively on the click
event.
● Dropdown: The three dropdowns have been created for selecting colours, fruits and animals with a
value already set to default.
● Button: A “try it” button has been created to show up the pop up box having Ok and Cancel button Simona Pitam
upon click event.
Scenario to be Automated
Scenario to be automated
● Launch the web browser and open the webpage
● Click on the “Google” hyperlink
● Navigate back to the original web page
● Select the “Green” in colour dropdown
● Select the “Orange” in the fruit dropdown
● Select the “Elephant” in the animal dropdown Simona Pitam
How to Handle Drop - Down Box
<div>
<select id="SelectID_One">
<option value="redvalue">Red</option>
<option value="greenvalue">Green</option>
<option value="greyvalue">Grey</option>
</select>
Selenium Example
// select the first operator using "select by value"
selectByValue.selectByValue("greenvalue");
Simona Pitam
Thread.sleep(5000);
Selenium Example
// / select the second dropdown using "select by visible text"
selectByVisibleText.selectByVisibleText("Lime");
Simona Pitam
Thread.sleep(5000);
CheckBox Element in Web Driver
By ID
If ID is given for the Radio Button/CheckBox and you just want to click on it irrespective of it’s value, then the
command will be like this:
WebElement radioBtn = driver.findElement(By.id("toolsqa"));
radioBtn.click();
Simona Pitam
With Is Selected CheckBox
If your choice is based on the pre-selection of the Radio Button/Check Box and you just need to select the
deselected Radio Button/Check Box. Assume there are two Radio Buttons/Check Boxes, one is selected by
default and you want to select the other one for your test. With IsSelected statement, you can get to
know that the element is selected or not.
Simona Pitam
Example with Value
// Find the checkbox or radio button element by Name
// Store the checkbox name to the string variable, using 'Value' attribute
if (sValue.equalsIgnoreCase("toolsqa")){
oCheckBox.get(i).click();
break;
Practise Exercise
Practice Exercise
There are different ways we can locate elements in WebDriver. In this WebDriver tutorial, we look at how we can use CSS
Selectors in more detail and with examples to interact with web elements.
1. It’s faster;
Simona Pitam
2. It’s more readable;
Let’s imagine we have a tag with the following attributes [id, class, name, value]
css = element_name[<attribute_name>='<value>']
We can use the same approach to locate by id and class attributes, however, there are short forms
that we can use to make it more readable.
CSS Selectors
We can use the same approach to locate by id and class attributes, however, there are short forms
that we can use to make it more readable.
Take extra care when using the short form notations, especially the . class notation as there could
be many web elements on the html source with the same class attribute.
CSS Selectors in Web Driver
The value of the display could either be “none” or “block” depending on the ajax call. In this
situation we have to locate the element by both class and style.
We could use
css="div[class='ajax_enabled'] [style='display:block']"
Simona Pitam
Locating Child Element
As can be seen, the individual list
<div id="child"><img src="./logo.png"></div> elements don’t have any id
associated with them. If we want to
To locate the image tag, we would use: locate the element with text
css="div#child img"
‘Orange’, we have to use “nth-of-
type”
Multiple Selections:
There are occasions when there are multiple child elements within the same parent element such as list elements
Simona Pitam
<ul id="fruit"> css="ul#fruit li:nth-of-
<li>Apple</li>
type(2)"
<li>Orange</li>
<li>Banana</li>
</ul>
Locating Child Element
Similarly, if we need to select the last child element, i.e. ‘Banana’, we can use
css="ul#fruit li:last-child"
Simona Pitam
Strings & Randomly Generated Id’s
We can also use string matchers to locate elements:
<div id="123_randomId">
<div id="randomId_456">
<div id="123_pattern_randomId">
To select the first div element, we would use ^= which means ‘starts with’: Simona Pitam
css="div[id^='123']"
Strings & Randomly Generated Id’s
To select second div element, we would use $= which means ‘ends with’:
css="div[id$='456']"
To select the last div element we would use *= which means ‘sub-string’
css="div[id*='_pattern_']"
Simona Pitam
css="div:contains(_pattern_)"
Attribute not Contain a Specific Value
In WebDriver, how do you find elements whose attribute contain values which you don’t want to
select? This CSS selector example shows how NOT to select by specific attribute value
Suppose you have many elements which share the same attribute and attribute value, but some of
those elements have other variables appended to the value. E.g:
As can be seen, all four divs contain “calendar-day-” but the first two also contain “unavailable”
which we don’t want.
The CSS selector for Not selecting the first two divs is
css = "div[class*=calendar-day-]:not([class*='unavailable'])"
Simona Pitam
Find Web Driver Elements
In the previous chapter of WebElement Commands, we learned different types to actions which can be
performed on a WebElement object. Thus the next thing to do is to interact with a web page to use
WebElement Commands/Actions. First thing to locate an element on the web page before interacting with it
and locating elements can be done on the WebDriver Instance(driver) itself or on a WebElement.
WebDriver gives us Find Element and Find Elements methods to locate element on the web page.
As in the previous chapters we learned that every method of the WebDriver either returns something or
return void(means return nothing). The same way findElementmethod of WebDriver returns WebElement.
Simona Pitam
Find Element in Web Driver
By ID
id(String id) : By – This is the most efficient and preferred way to locate an element, as most of the times
IDs are unique. It takes a parameter of String which is a Value of ID attribute and it returns a BY object to
findElement() method.
With this strategy, If no element has a matching id attribute, a NoSuchElementException will be raised.
Simona Pitam
Multi Browsing Testing in TestNG
In every project it is required to perform multi-browser testing to make sure that the functionality is working
as expected with every browser to give equal user experience to all of the wide range of audience. It takes a
considerable time to test everything on every browser and when we have used automation to reduce the
testing efforts then why don’t we perform the multi-browser testing using automation. TestNG gives us
functionality to perform same test on different browsers in a simple and easy way.
How to do it…
Simona Pitam
Multi Browsing TEsting Example
How to do it…
2) Pass ‘Browser Type’ as parameters using TestNG annotations to the before method of the TestNG class.
This method will launch only the browser, which will be provided as parameter.
Simona Pitam
Code Example
Code Example you can find in my git hub in following link:
https://github.com/simonapitam/seleniuntutorial
Simona Pitam
Creating XML File
Create a TestNG XML for running your test. Configure the TestNG XML for passing parameters i.e. to tell which
browser should be used for Running the Test.
Simona Pitam
Negative Testing in Selenium
While it is definitely important to verify that the software performs its basic functions as intended, it is equally or
more important to verify that the software is able to gracefully handle an abnormal situation. It is obvious that most
of the defects arise out of generating such situations with reasonable and acceptable creativity from the testers.
Simona Pitam
Simona Pitam
Positive Testing
Positive testing
Positive testing, many times referred to as “Happy path testing” is generally the first form of testing that a tester
would perform on an application. It is the process of running test scenarios that an end user would run for his use.
Hence as implied, positive testing entails running a test scenario with only correct and valid data. If a test scenario
doesn’t need data, then positive testing would require running the test exactly the manner in which it’s supposed to
run and hence to ensure that the application is meeting the specifications.
Sometimes there may be more than one way of performing a particular function or task with an intent to give the
end user more flexibility or for general product consistency. This is called alternate path testing which is also a kind
of positive testing. In alternate path testing, the test is again performed to meet its requirements but using the
different route than the obvious path. The test scenario would even consume the same kind of data to achieve the
same result.
Simona Pitam
Negative Testing
Negative testing
Negative testing commonly referred to as error path testing or failure testing is generally done to ensure the
stability of the application.
Negative testing is the process of applying as much creativity as possible and validating the application against
invalid data. This means its intended purpose is to check if the errors are being shown to the user where it’s
supposed to, or handling a bad value more gracefully.
The application or software’s functional reliability can be quantified only with effectively designed negative
scenarios. Negative testing not only aims to bring out any potential flaws that could cause serious impact on the
consumption of the product on the whole but can be instrumental in determining the conditions under which the
application can crash. Finally, it ensures that there is sufficient error validation present in the software.
Practical Example
Simona Pitam
Requirements for Test
Requirements:
Simona Pitam
Positive Cases
Positive test cases: Below are some positive testing scenarios for this particular pane.
Simona Pitam
Negative Cases
Negative test cases: Below are some negative testing scenarios for this particular pane.
Simona Pitam
Logging
Simona Pitam
Simona Pitam
Log4J
What is Log4j?
Log4j is a brilliant logging API available both on Java and .net framework. Advantages are:
– Log4j allows you to have a very good logging infrastructure without putting in any efforts.
– Log4j gives you the ability to categorize logs at different levels (Trace, Debug, Info, Warn, Error and Fatal).
– Log4j gives you the ability to direct logs to different outputs. For e.g. to a file, Console or a Database.
– Log4j gives you the ability to define the format of output logs.
– Log4j gives you the ability to write Asynchronous logs which helps to increase the performance of the
application.
– Loggers in Log4j follow a class hierarchy which may come handy to your applications.
If you are not able to understand any of these points than don’t worry. Things will get clearer as we approach
to the end of Log4j Tutorial series.
Simona Pitam
Log4j
Log4j
Log4j consists of four main components
– LogManager
– Loggers
– Appenders
– Layouts
With these comes some additional components which will be covered in the individual headings in following
tutorials
Log4j
package Log4jSample;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
//mainLogger is a logger object that we got from LogManager. All loggers are
//using this method only. We can consider LogManager as a factory to create
//Logger objects
static Logger mainLogger = LogManager.getLogger(SampleEntry.class.getName());
Simona Pitam
public static void main(String[] args) {
// TODO Auto-generated method stub
BasicConfigurator.configure();
mainLogger.info("This is just a logger");
}
}
Loggers
Logger
This is a class which helps you log information at different logging levels. In the above sample code you can
see that we have created a logger named mainLogger using the LogManager static class. Now we can use it to
write logs. As you can see we have mainLogger.info(“Comments that you want to log”) statement which logs
the string.
Simona Pitam