Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Home

Testing

SAP

Web

Live Projects

Accessing Links & Tables using Selenium


Webdriver

Must Learn!

Blog

Search
Search for...

In this tutorial, we are


going to learn about
accessing links & Tables
using Webdriver

Accessing Links
Links Matching a
Criterion
Links can be accessed
using an exact or partial
match of their link text. The examples below provide scenarios where
multiple matches would exist, and would explain how WebDriver
would deal with them.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

would deal with them.

Exact Match
Accessing links using their exact link text is done through the
By.linkText() method. However, if there are two links that have the
very same link text, this method will only access the first one. Consider
the HTML code below

Selenium
Tutorials
1) Introduction
2) Install IDE &
FireBug
3) Introduction IDE
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

3) Introduction IDE

When you try to run the WebDriver code below, you will be accessing
the first "click here" link

4) First Script
5) Locators
6) Enhancements
7) Intro WebDriver
8) Install

Webdriver
9) First WebDriver
Script
10) Forms &

As a result, you will automatically be taken to Google.

Webdriver
11) Links & Tables
12) Keyboard
Mouse Events
13) Selenium &
TestNG
14) Selenium Grid

Partial Match
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

15)
Parameterization
pdfcrowd.com

Accessing links using a portion of their link text is done using the
By.partialLinkText() method. If you specify a partial link text that has
multiple matches, only the first match will be accessed. Consider the
HTML code below.

16) Cross Browser


Testing
17) All About Excel
in Selenium
18) Creating
Keyword & Hybrid
Frameworks
19) Page Object
Model & Page
Factory
20) PDF, Emails
and Screenshot of
Test Reports
21) Using
Contains, Sibling,
Ancestor to Find
Element
22) Core

When you execute the WebDriver code below, you will still be taken to
Google.

Extensions
23) Sessions,
Parallel run and

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Parallel run and


Dependency
24) Handling Date
Time Picker
25)Using Apache
Ant with Selenium
26) Tutorial on
Log4j and
LogExpert with
Selenium
27) Maven &

Case-sensitivity
The parameters for By.linkText() and By.partialLinkText() are both
case-sensitive, meaning that capitalization matters. For example, in
Mercury Tours' homepage, there are two links that contain the text
"egis" - one is the "REGISTER" link found at the top menu, and the
other is the "Register here" link found at the lower right portion of the
page.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

Jenkins with
Selenium:
Complete Tutorial
28)Selenium with
HTMLUnit Driver &
PhantomJS
29)Database
Testing using

pdfcrowd.com

Selenium: Step by
Step Guide

Though both links contain the character sequence "egis", the


"By.partialLinkText()" method will access these two links separately
depending on capitilization of the characters. See the sample code
below.

Feedback

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Feedback
Your Feedback &
Ideas are very
important to us.
Please share your
suggestions here

All Links
One of the common procedures in web testing is to test if all the links
present within the page are working. This can be conveniently done
using a combination of the Java for-each loop and the
By.tagName("a") method. The WebDriver code below checks each
link from the Mercury Tours homepage to determine those that are
working and those that are still under construction.
package practice_webdriver;
import java.util.List;
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AllLinks {
public static void main(String[] args) {
String baseUrl = "http://newtours.demoaut.com/";
WebDriver driver = new FirefoxDriver();
String underConsTitle = "Under Construction: Mercury To
urs";
driver.manage().timeouts().implicitlyWait(5, TimeUnit.S
ECONDS);
driver.get(baseUrl);
List<WebElement> linkElements = driver.findElements(By.
tagName("a"));
String[] linkTexts = new String[linkElements.size()];
int i = 0;
//extract the link texts of each link element
for (WebElement e : linkElements) {
linkTexts[i] = e.getText();
i++;
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

}
//test each link
for (String t : linkTexts) {
driver.findElement(By.linkText(t)).click();
if (driver.getTitle().equals(underConsTitle)) {
System.out.println("\"" + t + "\""
+ " is under construction.");
} else {
System.out.println("\"" + t + "\""
+ " is working.");
}
driver.navigate().back();
}
driver.quit();
}
}

The output should be similar to the one indicated below.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Links Outside and Inside a Block


The latest HTML5 standard allows the <a> tags to be placed inside and
outside of block-level tags like <div>, <p>, or <h1>. The "By.linkText()"
and "By.partialLinkText()" methods can access a link located outside
and inside these block-level elements. Consider the HTML code below.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

The WebDriver code below accesses both of these links using


By.partialLinkText() method.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

The output above confirms that both links were accessed successfully
because their respective page titles were retrieved correctly.

Accessing Image Links


Image links are images that act as references to other sites or sections
within the same page. Since they are images, we cannot use the
By.linkText() and By.partialLinkText() methods because image links
basically have no link texts at all. In this case, we should resort to using
either By.cssSelector or By.xpath. The first method is more preferred
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

because of its simplicity.


In the example below, we will access the "Facebook" logo on the
upper left portion of Facebook's Password Recovery page.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

We will use By.cssSelector and the element's "title" attribute to access


the image link. And then we will verify if we are taken to Facebook's
homepage.
package practice_webdriver;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ImageLink {
public static void main(String[] args) {
String baseUrl = "https://www.facebook.com/login/identi
fy?ctx=recover";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
//click on the "Facebook" logo on the upper left portio
n
driver.findElement(By.cssSelector("a[title=\"Go to Face
book Home\"]")).click();
//verify that we are now back on Facebook's homepage
if (driver.getTitle().equals("Welcome to Facebook - Log
In, Sign Up or Learn More")) {
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

System.out.println("We are back at Facebook's homep


age");
} else {
System.out.println("We are NOT in Facebook's homepa
ge");
}
driver.quit();
}
}

Result

Reading a Table
There are times when we need to access elements (usually texts) that
are within HTML tables. However, it is very seldom for a web designer
to provide an id or name attribute to a certain cell in the table.
Therefore, we cannot use the usual methods such as "By.id()",
"By.name()", or "By.cssSelector()". In this case, the most reliable
option is to access them using the "By.xpath()" method.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

XPath Syntax
Consider the HTML code below.

We will use XPath to get the inner text of the cell containing the text
"fourth cell".

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Step 1 - Set the Parent Element (table)


XPath locators in WebDriver always start with a double forward
slash "//" and then followed by the parent element. Since we are
dealing with tables, the parent element should always be the <table>
tag. The first portion of our XPath locator should therefore start with
"//table".

Step 2 - Add the child elements


The element immediately under <table> is <tbody> so we can say that
<tbody> is the "child" of <table>. And also, <table> is the "parent" of
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

<tbody>. All child elements in XPath are placed to the right of their
parent element, separated with one forward slash "/" like the code
shown below.

Step 3 - Add Predicates


The <tbody> element contains two <tr> tags. We can now say that
these two <tr> tags are "children" of <tbody>. Consequently, we can
say that <tbody> is the parent of both the <tr> elements.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Another thing we can conclude is that the two <tr> elements are
siblings. Siblings refer to child elements having the same parent.

To get to the <td> we wish to access (the one with the text "fourth
cell"), we must first access the second <tr> and not the first. If we
simply write "//table/tbody/tr", then we will be accessing the first <tr>
tag.
So, how do we access the second <tr> then? The answer to this is to
use Predicates.
Predicates are numbers or HTML attributes enclosed in a pair of
square brackets "[ ]" that distinguish a child element from its
siblings. Since the <tr> we need to access is the second one, we shall
use "[2]" as the predicate.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

If we won't use any predicate, XPath will access the first sibling.
Therefore, we can access the first <tr> using either of these XPath
codes.

Step 4 - Add the Succeeding Child Elements Using the Appropriate


Predicates
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

The next element we need to access is the second <td>. Applying the
principles we have learned from steps 2 and 3, we will finalize our
XPath code to be like the one shown below.

Now that we have the correct XPath locator, we can already access the
cell that we wanted to and obtain its inner text using the code below. It
assumes that you have saved the HTML code above as
"newhtml.html" within your C Drive.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Accessing Nested Tables


The same principles discussed above applies to nested tables. Nested
tables are tables located within another table. An example is
shown below.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

To access the cell with the text "4-5-6" using the "//parent/child" and
predicate concepts from the previous section, we should be able to
come up with the XPath code below.

The WebDriver code below should be able to retrieve the inner text of
the cell which we are accessing.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

The output below confirms that the inner table was successfully
accessed.

Using Attributes as Predicates


If the element is written deep within the HTML code such that the
number to use for the predicate is very difficult to determine, we can
use that element's unique attribute instead.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

In the example below, the "New York to Chicago" cell is located deep
into Mercury Tours homepage's HTML code.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

In this case, we can use the table's unique attribute (width="270") as


the predicate. Attributes are used as predicates by prefixing them
with the @ symbol. In the example above, the "New York to Chicago"
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

cell is located in the first <td> of the fourth <tr>, and so our XPath
should be as shown below.

Remember that when we put the XPath code in Java, we should use
the escape character backward slash "\" for the double quotation
marks on both sides of "270" so that the string argument of By.xpath()
will not be terminated prematurely.

We are now ready to access that cell using the code below.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Shortcut: Use Firebug


If the number or attribute of an element is extremely difficult or
impossible to obtain, the quickest way to generate the XPath code is
thru Firebug.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Consider the example below from Mercury Tours homepage.

Step 1
Use Firebug to obtain the XPath code.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Step 2
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Look for the first "table" parent element and delete everything to the
left of it.

Step 3
Prefix the remaining portion of the code with double forward slash "//"
and copy it over to your WebDriver code.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

The WebDriver code below will be able to successfully retrieve the


inner text of the element we are accessing.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Summary
Accessing links using their exact match is done using By.linkText()
method.
Accessing links using their partial match is done using
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

By.partialLinkText() method.
If there are multiple matches, By.linkText() and By.partialLinkText()
will only select the first match.
Pattern matching using By.linkText() and By.partialLinkText() is casesensitive.
The By.tagName("a") method is used to fetch all links within a page.
Links can be accessed by the By.linkText() and By.partialLinkText()
whether they are inside or outside block-level elements.
Accessing image links are done using By.cssSelector() and By.xpath()
methods.
By.xpath() is commonly used to access table elements.

You Might Like


Top 20 Test Manager
Interview Questions

Free Business Analyst


Tutorial & Course

Download Test Plan


Template with Sample
Data

Big Data Testing:


Functional & Performance

Prev

open in browser PRO version

Next

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

AROUND THE WEB

The Borgata

New Jersey Man Hits Record Jackpot at


Borgata Casino

RealDose Nutrition

Do You Know What Your Weight Loss


Type Is (And What It Means)? Take A
Test.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Brilliant Earth

7 Engagement Ring Trends of 2015

Instant Checkmate

Have you ever Googled yourself? This


site reveals more info!
ALSO ON GURU99

Cookie Testing Tutorial with Sample Test Cases

Maven & Jenkins with Selenium: Complete Tutorial

1 comment

1 comment

Cmo utilizar Controller en LoadRunner 1 comment

Introduction concombre

13 Comments

Guru99

Recommend 3

open in browser PRO version

Share

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Join the discussion

Guest

8 months ago

One Question:
Suppose there are two links with same linked text. I want to access the second link. How do I do that?
14

Reply Share

Rajendra Narayan Mahapatra > Guest

17 days ago

driver.findElement(By.xpath("//a[contains(text(),'click here')][2]").click();

Reply Share

mira > Guest

a month ago

suppose 2nd link href="https://www.facebook.com"> then use


findElement(By.cssSelector("a[href*=facebook]")).click();

Reply Share

Max joseph > Guest

2 months ago

Ex::
If link Google is present in the Web Page..
Use the xpath like this:-->//*[contains(text(),'Google')][2]
Number 2 indicates that we are selecting 2nd GOOGLE link..
Check with the attached screenshot


open in browser PRO version

Reply Share

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Max joseph > Max joseph

2 months ago

PFA


Ankit

Reply Share

a year ago

This tutorial is THE best on web


10

Reply Share

Max joseph

9 months ago

Super GURU!!!!!! Great job, Excellent site for the beginners and for Non Technical guys who wants to start care
AUTOMATION!!!!
Keep Going...!!!!
6

Reply Share

naveen prabhu

2 months ago

Thank Guru.. This tutorial is very help full.. Clearly explained, best i have seen,.

Reply Share

sai krishna

4 months ago

Hi guru,
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

you are doing a great job.....


One Question.
My Application contain 4 links which i want to verify whether working or not.
One i can see directly on the page but the other 3 i am able to see when i mouseover on first link.
when i try to extract all links on page then i am getting only first link.
How to verify other 3 links which i get on mouse over.
Any help is appreciated...
Thanks....

Reply Share

anto

4 months ago

how to compare a table after updation using selenium c#

Reply Share

Sharmin Shultana

5 months ago

When webdriver get logout button it never check the other link........ it just logged out...

Reply Share

Hassan

5 months ago

Question: suppose i am reading through a table and i want to see if there is some text present in any of the rows
the table. if the text is found, test is successful otherwise test is failed.i have done eveything, i am stuck at how to
that test is successul or fail using if statement.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Reply Share

Vishnu Priya Amal Raj > Hassan

a month ago

Hi
I want to link on the 3 item in the table or array. How can i click 3 item in that.

Subscribe

Reply Share

Add Disqus to your site

Privacy

comments powered by Disqus

About
open in browser PRO version

Contact Us

Android
App

Are you a developer? Try out the HTML to PDF API

Certifications Execute
online

Interesting!
pdfcrowd.com

About us
Corporate
Training
Jobs

Contact us
FAQ
Write For Us

App

Copyright - Guru99 2015

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

ISTQB
Certification
MySQL
Certification
QTP
Certification
Testing
Certification

online
Execute Java
Online
Execute PHP
Online
Execute
PERL Online
Execute
Javascript
Execute
HTML
Execute
Python

Books to
Read!
Contest
Quiz

pdfcrowd.com

You might also like