Please enable JavaScript.
Coggle requires JavaScript to display documents.
Web Element Locator Strategies (2. DOM (Interaction (How Selenium…
Web Element Locator Strategies
1. What's in a web page
HTML(Skelton)
HTML element examples
<p>Hello, world!</p>
<a href="https://www.goole.com/">Go to Google</a>
<button type="button">Click Me!</button>
<h1>BIG NEWS!</h1>
<textarea rows="4" cols="50">Enter info here.</textarea>
<img src="smiley.gif" alt="Smiley face" width="42" height="42" />
HTML document example
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<div class="main-content">
<h1>BIG NEWS!</h1>
<p>HTML is awesome.</p>
<div>
</body>
</html>
Example explanation
<!DOCTYPE html>
- defines this document to be
HTML5
<html>
-
root
element of an HTML page
<head>
- contains
meta information
about the document
<title>
- specifies a
title
for the document
<body>
- contains the
visible page content
<h1>
- defines a
large heading
<p>
- defines a paragraph
HTML Tags
<tagname>
content goes here...
</tagname>
HTML
stands for
Hyper Text Markup Language
describes the
structure
of a Web page
consists of a
series of elements
elements
tell
the browser
how to display
the content
elements are
represented by tags
Tags label pieces of content such as "
heading
", "
paragraph
", "
table
", and so on
Browsers do not display the HTML tags, but
use them to render the content
of the page
CSS (Skin)
It can control things like - Colors, Size, Font, Position, Layout etc...
CSS example.css
body {
background-color: lightblue;
}
.main-content {
Font-family: Helvetica;
}
Ways to Add CSS
External CSS
(Add to head section of html)
<link rel="stylesheet" href="example.css"/>
Internal CSS
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
Inline CSS
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
What is CSS?
CSS stands for
Cascading Style Sheets
CSS describes
how HTML elements are to be displayed
on screen
CSS saves a lot of work. It
can control the layout of multiple web pages all at once
External stylesheets are stored in CSS files
Selector Declaration as an object of Property and value pair
JavaScript (muscle)
JavaScript example.js
alert("Here's some JavaScript!");
Where to Add js?
JS in head section
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
2. Internal example
Writing JS in body is preferred
<!DOCTYPE html>
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Internal JScript</title>
<script>
console.log("Welcome to JavaScript")
</script>
</head>
<body>
</body>
</html>
3. External JavaScript
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
use in HTML:
<script src="myScript.js"></script>
body is the recommended place to put external js file
1. Inline example
<DOCTYPE! html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<button onclick="alert('Hello world!')">Click Me</button>
</body>
</html>
2. DOM
Document Object Model
Programming interface for HTML and XML documents
Used to manipulate page
Searching for elements
Changing element content
Changing the HTML structure of the page
Changing the CSS styling of the page
The DOM is called an "object model"
because it presents the page as an object
(Language independent - but normally used with javascript)
Difference between element and it's locator
element
It's an OBJECT representing a live rendered HTML element on the page
locator
It's a QUERY that finds and returns specific elements from the DOM
Types
ID
Name
Class Name
CSS Selector
XPath
Standard way for finding elements in a web page, and that
every element can have a unique locator.
Interaction
Once element objects are obtained, there are
many ways to interact
with them.
JavaScript specifically provides methods, not only to change the
state
of the elements, but also to send
user like actions
to them.
Examples:
click()
textContent property
getAttribute()
setAttribute()
In fact, test frameworks like Jasmine, Mocha, Jest, and Cyprus all rely upon direct JavaScript calls within the browser.
How Selenium WebDriver find elements?
Selenium WebDriver relies upon locators to find elements (findElement) and interact with them.
The main difference for WebDriver calls is they
cannot change the state of elements
. They can only access the state and send interactions.
Furthermore,
WebDriver
calls
don't necessarily call JavaScript directly
. They operate using the
webDriver protocol
as implemented by each browser type.
webDriver can execute JavaScript code directly as well
3. Finding Live web element
(use Google Chrome's Developer Tools)
by Id
by name
by class name
4. CSS Selector
CSS Selectors are expressions that use pattern matching to find elements on a webpage.
CSS documents use these selectors to apply style to elements.
body
{
background-color: lightblue;
}
.main-content
{
Font-family: Helvetica;
}
These lines here for
body
and for
main-content
are actually CSS Selectors
tag name
is a valid CSS selector e.g div
by id -
#idvalue
notice # prefix
by classname -
.className
notice . prefix
combining multiple classes
.classA.classB.classC
(notice .)
direct parent-child
arrow - use > e.g ol > li
-
indirect child
- use blank space e.g div .abc (means class abc anywhere under div element)
locate by
multiple locators
- e.g
ol > li, ul > li
- notice comma
select based on
attribute
- e.g div[style]
select based on
attribute equality
e.g div[style="Bold"]
using with
attribute contains
e.g div[class*='result']
using advanced conditions with pseudo-classes e.g
div.result:not(.result--more)
using nth-child e.g
div.result:nth-child(3)
meaning 3rd item in the list
Basic examples:
Tag name: div
Class name: .result
Tag and class name: div.result
ID: #search_form_input
Descendants: div.cw div.result
Direct children: li.zcm__item > a
Multiple selectors: ol, ul
Attribute existence: [style]
Tag with attribute: div[style]
Tag with attribute equality: a[data-zci-link='images']
Tag with attribute contains: div[class*='results']
Logical not pseudoclass: div.result:not(.result--more)
Nth child pseudoclass: div.result:nth-child(5)
5. XPaths
XPaths are the strongest locator type
can uniquely identify element
can be used for XML and HTML
most complicated locator type
Examples
Another very powerful part of the XPath Syntax is it's set of
functions
which really help to make better attribute conditions.
The
contains function
is basically a
sub string operation
//div[
contains(@class
, 'result__snippet')]
The
starts-with
function
//div[
starts-with(@class
, 'result')]
The
not
function
Locate by Logical not function
//a[
not(contains(@class
, 'header'))]
you can also stack functions like:
//a[
not(starts-with(@class
, 'header'))]
Locate by Path from Root
/html/body
Locate by Tag Anywhere
//input
Mix the single slash and the double slash for direct children
//ul/li/a
Locate by Any Element
//
Locate by Any Descendants
//div//
based on attributes
//li[
class='item']
logical AND and OR operations for those conditional phrases
Locate by Attribute Condition AND
//img[
width<20][@height<20]
//img[
width<20
and
height<20]
Locate by Attribute Condition OR
//input[
name='q'
or
id='search_form_input']
Basic Xpath Rules and Examples
- Path from root
/html/body
- Tag anywhere
//input
- Direct Children
//ul/li/a
- Descendants
//div/a
- Any Element
//
- Any Descendants
//div//
- Attribute Value Equality
//li[
class='zcm__item']
- Attribute Condition AND
//img[
width<20][@height<20]
//img[
width<20
and
height<20]
- Attribute Condition OR
//input[
name='q'
or
id='search_form_input']
- Contains Function
//div[
contains(@class
, 'result')]
- Starts with function
//div[
starts-with(@class
, 'result')]
- Logical not function
//a[
not(contains(@class
, 'header'))]
Many other XPath functions
https://developer.mozilla.org/en-US/docs/Web/XPath/Functions
6. Advanced XPaths
what are specific things XPath can do that CSS Selectors cannot?
https://www.w3schools.com/xml/xpath_axes.asp
text, indices, and relational positions
The first major ability is selecting elements by text.
- Filter by text
//div[
contains(@class
, 'result__snippet')][contains(., 'bamboo')]
And we can see I have five results, one of them here containing the word "bamboo".
This little dot right here (the one before the comma and bamboo) will get the text displayed for the element.
There's also a text function like this:
contains(text(), 'bamboo')]
but that will get only the
direct textural content
of the element,
not the full text for many descendants included
. That's why typically when I check by text, I prefer the dot operator like this.
The second major ability for XPath is selecting elements by index.
(//div[
contains(@class
, 'result__snippet')])[3]
XPath indices start with 1
Caution
- text and indices make for fragile locators.
Element text also won't work well when a web page is translated into other languages for internationalization and localization.
recommend using text and indices in locators only when absolutely necessary
The third major ability for XPath is finding elements relative to other elements using advanced relationships.
To get all links on the page that have an image inside of them.
//a[.//img]
square brackets for the conditional expression
This XPath essentially says: "
I want to select the a elements for which inside of the anchor element, there is an image element as a descendant
."
The
dot
tells the XPath
to start from the current node
, and these
double slashes
just mean
any descendant.
XPath also has a bunch of axes for relationships to the current node.
brain-benders
However, they can be useful for tough cases
The 2 most useful are:
"preceding" and "following"
//a[
contains(@class
, 'def')][preceding::a[
class=
'abc']]
it means --
select all a elements with class def
which
comes after a element
(i.e
preceded by
)
having class abc
//a[
contains(@class
, 'def')][following::a[
class=
'abc']]
it means --
select all elements with class def
which comes before a element (i.e
followed by
)
having class abc
these axes will check preceding and following elements
anywhere in the DOM.
To limit the checks to children of the same parent, use the "
preceding-sibling
" and "
following-sibling
" axes instead.
7. Locator strategies
Few other locators:
Link Text
XPath equivalent
a[.="link text value"]
Partial Link Text
XPath equivalent
-a[contains(., "Partial Link Text")]
Tag
XPath equivalent
//a
Which one is the best?
Order of preference:
ID
Name
Class Name
CSS Selector
XPath without text or indexing
Link text or Partial link text
XPath with text and/or indexing
Tips:
Avoid using chrome dev tool to generate and use locators directly
Chrome's results can be helpful as a starting point, but don't simply copy and paste them into your tool or your automation code.
Chrome plugins to assist with locator
POM Builder
Eskry
Ranorex Selocity