0% found this document useful (0 votes)
13 views26 pages

Test Automation Tools and Frameworks Guide

The document discusses automated software testing, emphasizing the transition from manual to automated testing to improve software quality and efficiency. It outlines various test automation frameworks, types of tests suitable for automation, and the automation testing process, including tool selection and execution. Additionally, it introduces Selenium as a key tool for web application testing, detailing its components, benefits, and limitations.

Uploaded by

adlinstephi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views26 pages

Test Automation Tools and Frameworks Guide

The document discusses automated software testing, emphasizing the transition from manual to automated testing to improve software quality and efficiency. It outlines various test automation frameworks, types of tests suitable for automation, and the automation testing process, including tool selection and execution. Additionally, it introduces Selenium as a key tool for web application testing, detailing its components, benefits, and limitations.

Uploaded by

adlinstephi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT V TEST AUTOMATION AND TOOLS 6

Automated Software Testing, Automate Testing of Web Applications, Selenium: Introducing Web
Driver and Web Elements, Locating Web Elements, Actions on Web Elements, Different Web
Drivers, Understanding Web Driver Events, Testing: Understanding [Link], Adding Classes,
Packages, Methods to Test, Test Reports.
30 PERIODS

Automated Software Testing

Automated Testing is a technique where the Tester writes scripts on their own and uses suitable Software
or Automation Tool to test the software. It is an Automation Process of a Manual Process. It allows for
executing repetitive tasks without the intervention of a Manual Tester.

●​ It is used to automate the testing tasks that are difficult to perform manually.
●​ Automation tests can be run at any time of the day as they use scripted sequences to examine the
software.
●​ Automation tests can also enter test data can compare the expected result with the actual result
and generate detailed test reports.
●​ The goal of automation tests is to reduce the number of test cases to be executed manually but not
to eliminate manual testing.
●​ It is possible to record the test suit and replay it when required.

Why Transform From Manual to Automated Testing?

In the year 1994, An aircraft completing its Routine flight crashed just before landing. This was due to
some bug or defect in the Software. The Testers didn’t even care about the final testing and hence this
accident happened. So in order to replace for few of the Manual Tests (mandatory), there is a need for
Automation Testing. Below are some of the reasons for using automation testing:

Quality Assurance: Manual testing is a tedious task that can be boring and at the same time error-prone.
Thus, using automation testing improves the quality of the software under test as more test coverage can
be achieved.
Error or Bug-free Software: Automation testing is more efficient for detecting bugs in comparison to
manual testing.

No Human Intervention: Manual testing requires huge manpower in comparison to automation testing
which requires no human intervention and the test cases can be executed unattended.

Increased test coverage: Automation testing ensures more test coverage in comparison to manual testing
where it is not possible to achieve 100% test coverage.

Testing can be done frequently: Automation testing means that the testing can be done frequently thus
improving the overall quality of the software under test.

Test Automation Frameworks

Some of the most common types of automation frameworks are:

Linear framework: This is the most basic form of framework and is also known as the record and
playback framework. In this testers create and execute the test scripts for each test case. It is mostly
suitable for small teams that don’t have a lot of test automation experience.

Modular-Based Framework: This framework organizes each test case into small individual units
knowns as modules each module is independent of the other, having different scenarios but all modules
are handled by a single master script. This approach requires a lot of pre-planning and is best suited for
testers who have experience with test automation.

Library Architecture Framework: This framework is the expansion of a modular-based framework


with few differences. Here, the task is grouped within the test script into functions according to a common
objective. These functions are stored in the library so that they can be accessed quickly when needed. This
framework allows for greater flexibility and reusability but creating scripts takes a lot of time so testers
with experience in automation testing can benefit from this framework.

Which Tests to Automate?

Below are some of the parameters to decide which tests to automate:

Monotonous test: Repeatable and monotonous tests can be automated for further use in the future.

A test requiring multiple data sets: Extensive tests that require multiple data sets can be automated.
Business critical tests: High-risk business critical test cases can be automated and can be scheduled to
run regularly.

Determinant test: Determinant test cases where it is easy for the computer to decide whether the test is
failed or not can be automated.

Tedious test: Test cases that involve repeatedly doing the same action can be automated so that the
computer can do the repetitive task as humans are very poor at performing the repetitive task with
efficiency, there increase the chances of error.

Automation Testing Process

Test Tool Selection: There will be some criteria for the Selection of the tool. The majority of the criteria
include: Do we have skilled resources to allocate for automation tasks, Budget constraints, and Do the
tool satisfies our needs?

Define Scope of Automation: This includes a few basic points such as the Framework should support
Automation Scripts, Less Maintenance must be there, High Return on Investment, Not many complex
Test Cases

Planning, Design, and Development: For this, we need to Install particular frameworks or libraries, and
start designing and developing the test cases such as NUnit, JUnit, QUnit, or required Software
Automation Tools

Test Execution: Final Execution of test cases will take place in this phase and it depends on Language to
Language for .NET, we’ll be using NUnit, for Java, we’ll be using JUnit, for JavaScript, we’ll be using
QUnit or Jasmine, etc.

Maintenance: Creation of Reports generated after Tests and that should be documented so as to refer to
that in the future for the next iterations.

Automate Testing of Web Applications

Testing a web application is a highly crucial and essential part of software development. It is a software
practice that can be automated with the combination of different tools related to it. It eventually reduces
the need for human intervention and leads to incredible speed, reliability, and efficiency in it. It can be
implemented and accomplished using various types of software automation testing tools and types of it
for that particular purpose and eventually increase the performance and enhance the user interface of it.

Why do we need it?

The rise in the adoption of concepts such as agile is forcing companies to rethink the way they develop
software. Automation, versatility, cross-team combination, and changeability are the main components for
the successful adoption of agile testing.

As with all it, the process is onerous when performed manually, and there is the risk of human error or
fallacy. Automation is to be introduced as it is what we call less human intervention - generally
implemented to reduce risk, lower costs, and increase execution - is the main explanation for solving this
issue.

What are the types of Web App Testing that can be automated?

The various types of automated Web application testing are mentioned below:

Functional Testing
It is used to ensure that the functionality specified as part of the software requirements works deliberately
from the end user’s perspective. Functional testing is a day-to-day knowledge that the test process that
uncovers the most bugs lets the end-user explore the software.

Web Usability Testing

It can automate the research process, mainly when working with remote participants. User testing
software aids you to connect with users and automatically gathers data without any deliberation and then
displays who hit their goals or where users struggled, allowing you to build better products for happier
customers, you can even call it automated end-user experience testing. Automating it can save resources,
reduce cost, get an overall test coverage, and have an enhanced return of investment(ROI) for design.

Performance Testing

Automation and performance monitoring go hand-in-hand. Automation permits you to check and monitor
the load and performance of the particular application 24/7, so when things go out of control, it
automatically alerts someone, or you create a ticket in a service desk. Not only that, automation allows us
to monitor performance in physical servers, virtual hosts, virtual machines, and applications giving us an
enhanced output.

Website Compatibility Testing

To deliver a great enhanced end user experience, web apps and websites should work across various
browsers, browser versions, and devices, including mobile.

It hosts all the possible combinations of browsers, operating systems,and devices in our infrastructure to
support automated web testing.

Security Testing

Automating web application security testing can help minimize human errors and also decrease the cost
factor. For automating security testing in a web application, we need massive test coverage, the accuracy
of test results, scheduled security tests,

Choosing appropriate tools and, in the end, to implement and iterate the process.

What are the best tools for it?


The below described are the best tools for web application automated testing:

Katalon Studio

What do we like?

It is convenient and accessible to different types of testers(inclusive and exclusive of both programmings).

It is flexible and easy to use with its quick, powerful features(robust).

It also supports image-based testing, which is quite an enhanced and new feature.

It supports integration with Jenkins.

It’s known for its hassle-free, customizable execution workflow.

It can support web application automation, API Testing, Mobile Testing.

It has built-in support for creating test cases, generating test scripts, reporting results, recording actions. It
is famous for its built-in support for groovy(java) scripting languages.

It can be integrated with CI/DevOps workflow and other tools.


What do we dislike?

It only supports groovy(java). So it is feasible for java users only.

It is not an open-source tool. It is closed source code, and it further results in a small community.

There are some performance issues, like more interruption causing the device to slow down.

Cucumber

What do we like?

It is a collaborative tool based on behavior-driven development.

It is an open-source automated software testing tool.

It helps in writing acceptance tests for our web applications.

It provides the amalgamation of both test documentation and its specification(specs).

It supports multi-languages like python,perl,ruby,.net etc.

It is provided with cross-platform compatibility.

It can be integrated with DevOps tools like GIT, Jenkins, etc., for better enhancement.

What do we dislike?
Integration and its dependency on generating reports through plugins can be challenging enough.

Every time a new attribute or feature undergoes it, we have to ensure all current steps and validate them to
see if they can be used.

Selenium

What do we like?

It is the most versatile automated software testing tool.

This tool is open-source and widely supports all languages and frameworks.

It comes with heavy library packages.

It supports cross-browser automation, API automation, and database automation.

Testers can use it for regression, exploratory testing, and quick reproduction of bugs.

It can be beneficial in parallel test execution techniques.

It is highly known for its flexibility with ease of implementation.

Its integration with gauge automation framework, Galen framework, lambda test, etc., is trending
nowadays.

What do we dislike?
Test Maintenance in selenium can become cumbersome and even expensive sometimes.

Selenium requires coding skills, if not exceptional but above average, though.

It is only supported for web applications, though.

Technical support and its reliability can cause problems, though.

Flaky tests can be a big problem as they generate false negatives and false positives or vice versa.

Selenium: Introducing Web Driver and Web Elements

Selenium refers to a suite of tools that are widely used in the testing community when it comes to
cross-browser testing. Selenium cannot automate desktop applications; it can only be used in browsers. It
is considered to be one of the most preferred tool suites for automation testing of web applications as it
provides support for popular web browsers which makes it very powerful.

It supports a number of browsers (Google Chrome 12+, Internet Explorer 7,8,9,10, Safari 5.1+, Opera
11.5, Firefox 3+) and operating systems (Windows, Mac, Linux/Unix).

Selenium Components

The Selenium test suite comprises four main components:

Selenium IDE
Selenium IDE (Integrated Development Environment) is primarily a record/run tool. It is an Add-on or an
extension available for both Firefox and Chrome that generates tests quickly through its functionality of
record and playback. You don’t need to learn any test scripting language for authoring any functional
tests.

Selenium RC
In the case of working with Selenium RC (Remote Control), one must have good knowledge of at least
one programming language. This tool allows you to develop responsive design tests in any scripting
language of your choice. Server and client libraries are the two main components of Selenium RC. Its
architecture is complex and it has its limitations.

Selenium WebDriver
Selenium WebDriver is an enhanced version of Selenium RC. It was introduced in the market to
overcome the limitation faced in Selenium RC. Though it is an advanced version of RC, its architecture is
completely different from that of RC. Just like Selenium RC, Selenium WebDriver too supports multiple
programming platforms to provide wider flexibility and requires knowing any one programming
language.

Selenium Grid
Selenium Grid is a tool that is used for concurrent execution of test cases on different browsers, machines,
and operating systems simultaneously. This tool makes Cross-browser compatibility testing very easy.
There are two versions of the Selenium Grid – the older version is known as Grid 1 and the recent version
is known as Grid 2.

Selenium WebDriver
Selenium WebDriver is a web framework that permits you to execute cross-browser tests. This tool is
used for automating web-based application testing to verify that it performs expectedly.

Selenium WebDriver allows you to choose a programming language to create test scripts. As discussed
earlier, it is an advancement over Selenium RC to overcome a few limitations. Selenium WebDriver is not
capable of handling window components, but this drawback can be overcome by using tools like Sikuli,
Auto IT, etc.
Selenium WebDriver Framework Architecture

WebDriver Architecture is made up of four major components:

●​ Selenium Client library


●​ JSON wire protocol over HTTP
●​ Browser Drivers
●​ Browsers

Selenium Client Libraries/Language Bindings

Selenium provides support to multiple libraries such as Ruby, Python, Java, etc as language bindings have
been developed by Selenium developers to provide compatibility for multiple languages. For instance, if
you want to use the browser driver in Python, use the Python Bindings. You can download all the
supported language bindings of your choice from the official site of Selenium.

JSON Wire Protocol


JSON is an acronym for JavaScript Object Notation. It is an open standard that provides a transport
mechanism for transferring data between client and server on the web. It provides support for various data
structures like arrays and objects which makes it easier to read and write data from JSON.

Browser Drivers

Selenium provides drivers specific to each browser and without revealing the internal logic of browser
functionality, the browser driver interacts with the respective browser by establishing a secure connection.
These browser drivers are also specific to the language which is used for test case automation like C#,
Python, Java, etc.

Browsers
As discussed earlier, Selenium provides support for multiple browsers like Chrome, Firefox,
Safari, Internet Explorer etc.

Basic Steps in a Selenium WebDriver Script

●​ Create a WebDriver instance.


●​ Navigate to a webpage.
●​ Locate a web element on the webpage via locators in selenium.
●​ Perform one or more user actions on the element.
●​ Preload the expected output/browser response to the action.
●​ Run test.
●​ Record results and compare results from them to the expected output.

Benefits and Limitations of Selenium WebDriver


Benefits of Selenium WebDriver

●​ It is one of the most popular Open-Source tools and is easy to get started with for testing

web-based applications. It also allows you to perform cross browser compatibility testing.

●​ Supports multiple operating systems like Windows, Mac, Linux, Unix, etc.

●​ It provides compatibility with a range of languages, including Python, Java, Perl, Ruby, etc.

●​ Provides support for modern browsers like Chrome, Firefox, Safari, and Internet Explorer.

●​ Selenium WebDriver completes the execution of test scripts faster when compared to other tools

●​ More Concise API (Application Programming interface) than Selenium RC’s

●​ It also provides compatibility with iPhoneDriver, HtmlUnitDriver, and AndroidDriver+

Selenium WebElement

A WebElement, in this case, a WebElement in Selenium is essentially an HTML element on a website.

HTML documents consist of HTML elements. Each HTML element consists of a start tag and an end tag.

The content lies between the tags.

Syntax

<start tag> content </end tag>

HTML elements can contain other elements. Every HTML document carries such HTML elements.

WebElement Selenium WebDriver methods apply to almost all DOM elements on a web page.
Each WebElement is represented in Selenium via the WebElement interface – which is used by Selenium

to interact with visible and invisible elements on the web page.

Here’s an example of a WebElement in Selenium command:

WebElement element = [Link]([Link](“UserName“));

This command returns either the element being searched for or returns null/void.

List of Selenium WebElement Commands

1. sendKeys() command

sendKeys command allows the user to type content automatically into an editable field while executing

tests. These fields are web elements that can be identified using locators like element id, name, class

name, etc.

Syntax:

[Link](“text”);

This method uses CharSequence as a parameter. It returns nothing. It works with text entry elements such

as INPUT and TEXTAREA.

Code:

// Create WebElement

WebElement elesendKeys = [Link]([Link]("TextBox"));

// Perform sendKeys operation

[Link]("Cheese");

// OR

// Send value to particular WebElement e.g: Textbox.

[Link]([Link]("TextBox")).sendKeys("Cheese");
2. isDisplayed() command

The isDisplayed command in Selenium verifies if a particular element is present and displayed. If the

element is displayed, then the value returned is true. If not, then the value returned is a

NoSuchElementFound exception.

Syntax:

[Link]();

The code below verifies if an element with the id attribute value next is displayed.

boolean eleSelected= [Link]([Link]("xpath")).isDisplayed();

WebElement element = [Link]([Link]("UserName"));

boolean status = [Link]();

//Or can be written as

boolean status = [Link]([Link]("UserName")).isDisplayed();

3. isSelected() command

This command only works on input elements such as radio buttons, checkboxes, select options, and menu

items. It is used to determine if an element is selected. If the specified element is selected, the value

returned is true. If not, the value returned is false.

Syntax:

[Link]();

Code:
WebElement element = [Link]([Link]("Sex-Male"));

boolean status = [Link]();

//Or can be written as

boolean staus = [Link]([Link]("Sex-Male")).isSelected();

4. submit() command

This command is handy when interacting with forms (or elements within a form) on a web page. It

doesn’t require a parameter and returns nothing.

As evident from its name, the command submits relevant information (as required) on a website. If the

action triggered by this command changes the current web page, the method will wait until the new page

loads.

Syntax:

[Link]();

Code:

WebElement element = [Link]([Link]("SubmitButton"));

[Link]();

//Or can be written as

[Link]([Link]("SubmitButton")).submit();

WebElement element = [Link]([Link]("SubmitButton"));

[Link]();

//Or can be written as


[Link]([Link]("SubmitButton")).submit();

5. isEnabled() command

This WebElement in Selenium command verifies if an element is enabled on the web page. If the element

is enabled, it returns a true value. If not, it returns a false value.

Syntax:

[Link]();

The code below verifies if an element with the id attribute value next is enabled.

boolean eleEnabled= [Link]([Link](“xpath”)).isEnabled();

// Create WebElement

WebElement eleEnabled = [Link]([Link]("TextBox"));

// Perform isEnabled operation

[Link]();

// OR

// Verify WebElement is Enabled or Not? e.g: Radio / Checkbox.

[Link]([Link]("Text")).isEnabled();

6. getLocation() command

This command retrieves the location of a specified element on a web page. It does not require a parameter

and returns the Point object as its result. The X and Y coordinates of the element can be derived from the

Point object returned.


Syntax:

[Link]();

Code:

WebElement element = [Link]([Link]("SubmitButton"));

Point point = [Link]();

[Link]("X cordinate : " + point.x + "Y cordinate: " + point.y);

7. clear( ) command

When using this WebElement in Selenium command, its value will be cleared if the element in question is

a text entry. It doesn’t require a parameter and returns nothing.

Syntax:

[Link]();

The clear() method does not affect other web elements. The text entry elements here are INPUT and

TEXTAREA.

Code:

// Create WebElement

WebElement eleClear = [Link]([Link]("TextBox"));

// Perform clear operation

[Link]();

// OR

// Clear particular WebElement e.g: Textbox.

[Link]([Link]("TextBox")).clear();
8. getText() command

This command retrieves the text within a specific web element. This includes the inner text as well as the

sub-elements sans whitespace. It doesn’t require a parameter and returns a string value. This method is

often used to verify labels, messages, error, and other elements (involving text) displayed to website

visitors.

Syntax:

[Link]();

Code:

// Create WebElement

WebElement elegetText = [Link]([Link]("TextBox"));

// Perform getText operation

[Link]();

// OR

// Get text of Particular WebElement &amp; Store into String

[Link]([Link]("TextBox")).getText();

9. getTagName() command

This method retrieves the tag name of the specified element. It does not require a parameter and returns a

string value as its result.

Syntax:

[Link]();

This command does not return the value of the name attribute. It returns the tag. For example, if the code

is <input name=”foo”/>, then this command will return the tag, i.e. “input”.

Code:
// Create WebElement

WebElement elegetTagName = [Link]([Link]("TextBox"));

// Perform getTagName operation

[Link]();

// OR

// Able to get TagName of Particular WebElement &amp; Store into String

[Link]([Link]("TextBox")).getTagName();

// Create WebElement

WebElement elegetTagName = [Link]([Link]("TextBox"));

// Perform getTagName operation

[Link]();

// OR

// Able to get TagName of Particular WebElement &amp; Store into String

[Link]([Link]("TextBox")).getTagName();

10. getCssValue() command

This command retrieves the CSS property value of a specified element. It does not require a parameter

and returns a string value as its result.

Syntax:

[Link]();

Color values must be returned as rgba strings. For example, if the “background-color” property is set as

“green” in the HTML source, the value returned by the command will be “rgba(0, 255, 0, 1)”.

Shorthand CSS properties (e.g. font, background, border, margin, border-top, margin-top, padding,

padding-top, outline, list-style, pause, cue) are not returned, as required with DOM CSS2 specifications.

Access the longhand properties directly in order to access the desired values.

Code:
//Locating textBox element using CSS Selector

WebElement textBox = [Link]([Link]("div#textBox "));

//Performing sendKeys operation on the element

[Link]("stqatools");

11. getAttribute() command

This command retrieves the attribute value of a specified element. It uses String as the parameter and

returns a string value as its result.

Syntax:

[Link]();

Code:

WebElement element = [Link]([Link]("SubmitButton"));

String attValue = [Link]("id"); //This will return "SubmitButton"

12. click() command

The click() command lets the tester replicate the click action on a button, link, radio button or checkbox.

In Webdriver, the click occurs after the element is found. In Selenium IDE, the recorder identifies the

element, the command itself performs the click.

Syntax:

[Link]();

Code:

// Create WebElement

WebElement eleclick = [Link]([Link]("TextBox"));

// Perform click operation

[Link]();

// OR

// Click on any WebElement e.g: Button.


[Link]([Link]("Button_Id")).click();

// Create WebElement

WebElement eleclick = [Link]([Link]("TextBox"));

// Perform click operation

[Link]();

// OR

// Click on any WebElement e.g: Button.

[Link]([Link]("Button_Id")).click();

13. getSize() command

This command retrieves the height and width of a specific rendered element. It does not require a

parameter and returns the Dimension object as its result.

Syntax:

[Link]();

Code:

WebElement element = [Link]([Link]("SubmitButton"));

Dimension dimensions = [Link]();

[Link](“Height :” + [Link] + ”Width : "+ [Link]);

Locating Web elements

Locators in Selenium come into action in the fourth step above after the Selenium WebDriver is initialized

and loaded the webpage to be tested. A locator enables testers to select an HTML DOM element to act on.

This post examines the top 8 locators in Selenium WebDriver.

Knowing how to use different locators correctly is key to building better automation scripts. If the test

script is not able to identify which element it needs to interact with, the test will fail before it can begin.
Different Types of Locators in Selenium

Here’s a snapshot overview of top 8 locators in Selenium:

●​ By CSS ID: find_element_by_id

●​ By CSS class name: find_element_by_class_name

●​ By name attribute: find_element_by_name

●​ By DOM structure or Xpath: find_element_by_xpath

●​ by tagName: find_element_by_tag_name()

●​ By link text: find_element_by_link_text

●​ By partial link text: find_element_by_partial_link_text

●​ By HTML tag name: find_element_by_tag_name

While all these locators return single elements, one may use the .find_elements() method to find multiple

elements. Let’s further explore the different types of locators in Selenium and how to use them.

Locate Elements by CSS ID

This is by far the simplest method of locating an element. The CSS ID, stored in the id attribute of an

HTML DOM element, is unique for every element in the page by design. Thus, an ID can uniquely

identify an element.

To use this feature, one needs to call the .find_element_by_id() method of the webdriver class. Here is the

usage for it.

from selenium import webdriver

driver = [Link]('./chromedriver')

[Link]("[Link]

search_bar = driver.find_element_by_id("id-search-field")

If there is no DOM element with the ID that one is searching for, a NoSuchElementException is raised,

which one can account for, by using a try-catch block.

Locate Elements by CSS Class


A second strategy for locating elements on a page is to search by the class name. The class name is stored

in the class attribute of an HTML tag. By design, a CSS class applies to a group of DOM elements. The

.find_element_by_class_name() method only returns the first element with the matching class. It raises a

NoSuchElementException if no element exists with the given class name. Here is how to use the method

in the driver.

from selenium import webdriver

driver = [Link]('./chromedriver')

[Link]("[Link]

# Returns first element with matching class

first_search_bar = driver.find_element_by_class_name("id-class-name")

Locate Elements by Name

In HTML5, form elements often have a name attribute associated with them. The

.find_element_by_name() method only returns the first element with the matching class. If multiple

elements of the same name exist, the first matched element will be returned. No matching elements result

in a NoSuchElementException error.

Consider the following form:

<form id="loginForm">

<input name="name" type="text" value="First Name" />

<input name="name" type="text" value="Last Name" />

<input name="email" type="text" value="Business Email" />

<input name="password" type="password" />

<input name="continue" type="submit" value="Sign Me Up" />

</form>

Locate Elements by XPath


If one has failed to identify an element by ID, class, or name, one would need to locate the element

through its XML path. This process may also be implemented while reading an XML document. In this

tutorial, we explore the use of relative paths, as absolute paths are prone to errors with the slightest

change in the HTML structure.

We will use the .find_element_by_xpath() method to locate an appropriate element in the document. The

argument that the .find_element_by_xpath() method takes is the path to the element.

To find the email input field in the above HTML form example, use the following code:

email_input = driver.find_element_by_xpath("//form[input/@name='email']")

This code snippet searches for the first form element of the page. Within this form, it searches for input

with the name, which equals the value email, thus narrowing down to the required element.

Next, let us try to locate the form’s first and last names input element above.

first_name = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")

last_name = driver.find_element_by_xpath("//form[@id='loginForm']/input[2]")

The method first searches for a form with the ID login form and then selects the form’s first and second

input elements as the first and last names.

Locate Elements by tagName

In addition to the popular methods we have discussed, there are a few other element locators in the

Selenium WebDriver that testers may wish to explore.

One can locate elements by their HTML tag name using the .find_element_by_tag_name() method.

page_heading = driver.find_element_by_tag_name('h1')

Locate Elements by linkText

One can also search for a hyperlink element using the link text. One can either use the

.find_element_by_link_text() method to search for the exact link’s text.

# Exact Link Text

click_here_link = driver.find_element_by_link_text('Click Here')


Locate Elements by partialLinkText

Or one can also search for a hyperlink element using the partial link text

.find_element_by_partial_link_text() method to search for a partial text.

# Partial Link Text

click_here_link = driver.find_element_by_partial_link_text('Click')

Locate Multiple Elements

In this tutorial, we have discussed methods that locate only single elements. One may want to select a

group of elements and then iterate through them. The .find_elements() method helps in finding multiple

elements in the DOM structure.

Here are typical examples of the usage of the .find_elements() method. To find all input elements of a

form with ID loginForm, use the following snippet –

from [Link] import By

all_inputs = driver.find_elements([Link], '//form[@id='loginForm']/input')

To locate all elements with a class name, use the following code –

from [Link] import By

all_elements = driver.find_elements(By.CLASS_NAME, 'my-css-class')

In addition to this, the By class has the following attributes:

[Link]: search using the CSS ID

By.LINK_TEXT: search using the exact link text

By.PARTIAL_LINK_TEXT: search using partial link text

[Link]: search using the name attribute

By.TAG_NAME: search using the HTML tag name

You might also like