0% found this document useful (0 votes)
82 views11 pages

Relative Xpath

Relative XPath uses '//' to represent any child element descendants. It provides examples of relative XPath expressions and elements they would match. It also discusses common interview questions about the differences between '/' and '//' and writing XPath to match all links and images on a page.

Uploaded by

prabhakar r
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)
82 views11 pages

Relative Xpath

Relative XPath uses '//' to represent any child element descendants. It provides examples of relative XPath expressions and elements they would match. It also discusses common interview questions about the differences between '/' and '//' and writing XPath to match all links and images on a page.

Uploaded by

prabhakar r
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
You are on page 1/ 11

Relative xpath: -

In relative xpath, we use ‘//’ which represents any child element (descendants)

Example:-
Relative xpath Matching Element
//td SQL, 300, Java, 400
//tr[1]/td SQL,300
//tr[1]/td[1] SQL
//tr[1]/td[2] 300
//tr[2]/td Java, 400
//tr[2]/td[1] Java
//tr[2]/td[2] 400
//td[1] OR //tr/td[1] SQL,java
//td[2] OR //tr/td[2] 300,400
//tr[1]/td[1] | //tr[2]/td[2] SQL,400
//tr[1]/td[1] | SQL,300,400
//tr[1]/td[2] |
//tr[2]/td[2]
OR
//tr[1]/td | //tr[2]/td[2]

Interview Questions: -
Q. What is the difference between / and // ?
 / represent immediate child and // represents any child or descendant.

Q. Derive the xpath which matches with all the links present on the webpage?
 //a

Q. Difference between //a and //table//a ?


 //a matches with all the links which are present in the entire page. //table//a matches with all the links
which are present inside all the tables.

Q. Write xpath which matches all the images and links present on the webpage?
 //img | //a

WebDriver driver = new FirefoxDriver();


Driver.get("file:///Users/guruprasadsr/Desktop/D-Drive/Selenium/Java_Tutorials/HTMLs/DemoFNLN.html");
driver.findElement(By.xpath(“//input”)).sendkeys(“a”);
driver.findElement(By.xpath(“//input[1]”)).sendkeys(“b”);
driver.findElement(By.xpath(“//input[2]”)).sendkeys(“c”);

When we get the driver object, the below are the methods that we can perform operation on a driver. In
IDE like eclipse, when we enter driver. and click on space bar, it will show all the below methods.All these
come under WebElement

1. get()
2. getCurrentUrl();
3. getTitle()
4. findElements()
5. findElement()

15
6. getPageSource()
7. close()
8. quit()
9. getWindowHandles()
10. getWindowHandle()
11. navigate()
12. manage()
13. switchTo()
Other methods:
14. getAttribute()
15. getLocation()
16. click()
17. clear()

1. Method Name :- get()


Syntax: get(url)
Example: driver.get();
Purpose: It will load a new web page in the current browser window. This is done using an http
get operation, and the method will block until the load is complete.
Parameters: URL - The URL to load and it should be a fully qualified URL

2. Method Name: getCurrentUrl()


Syntax: getCurrentUrl()
Example: driver.getCurrentUrl();

Returns: The URL of the page currently loaded in the browser

3. Method Name: getTitle()


Syntax: getTitle()
Example: driver.getTitle();
Purpose: Gets the title of the current web page.
Returns: The title of the current page, with leading and trailing white space stripped, or null if one is
not already set

4. Method Name: findElements()


Syntax: findElements(By by)
Example: driver.findElements(By.xpath("//");

16
Purpose: Find all elements within the current page using the given mechanism.
Parameters: By - The locating mechanism to use
Returns: A list of all WebElements, or an empty list if nothing matches
5. Method Name: findElement()
Syntax: WebElement findElement(By by)
Example: driver.findElements(By.xpath("//");
Purpose: Find the first WebElement using the given method.
Parameters: By - The locating mechanism
Returns: The first matching element on the current page Throws: NoSuchElementException - it will return exception if no
matching elements are found

6. Method Name: getPageSource()


Syntax: getPageSource()
Example: driver.getPageSource();
Purpose: Get the source of the currently loaded page. If the page has been modified after loading (for example, by
Javascript) there is no guarantee that the returned text is that of the modified page.
Returns: The source of the current page

7. Method Name: close()


Syntax: void close()
Example: driver.close();
Purpose: Close the current window, if there are multiple windows, it will close the current window which is active and quits the
browser if it's the last window opened currently.

8. Method Name: quit()


Syntax: void quit()
Example: driver.quit();
Purpose: Quits this driver instance, closing every associated window which is opened.
9. Method Name: getWindowHandles()
Syntax: Set getWindowHandles()
Example: driver.getWindowHandles();
Purpose: Return a set of window handles which can be used to iterate over all the open windows of this Webdriver instance
by passing them to switchTo().WebDriver.Options.window()
Returns: A set of window handles which can be used to iterate over all the open windows.

10. Method Name: getWindowHandle()


Syntax: String getWindowHandle()
Example: driver.getWindowHandle();
Parameter: Return an opaque handle to this window that uniquely identifies it within this driver instance. This can be used to
switch to this window at a later date switchTo
WebDriver.TargetLocator switchTo() The next future commands will be performed to a different frame or
window.
11. Method Name: navigate()
Syntax: WebDriver.Navigation navigate()
Example: driver.navigate.to("");
Purpose: An abstraction allowing the driver to access the browser's history and to navigate to a given URL.
Returns: A WebDriver.Navigation that allows the selection of what to do next

17
Click here to know more on Navigation methods
12. Method Name: manage()
Syntax: WebDriver.Options manage()

Purpose: Gets the Option interface

Returns: An option interface

13. switchTo()
Syntax: Webdriver.TargetLocator()switchto()
Purpose:Send future commands to a different frame or window.

Returns:A TargetLocator which can be used to select a frame or window

3. Xpath by attribute:
Using relative xpath we can reduce the length of expression but it may match with multiple elements
even after using index.In order to identify the element uniquely we can use attribute in the xpath expression
using following syntax:

//tag[@AttributeName=’AttributeValue’]

Example: //input[@placeholder=’Username’]

IQ 1]Can we use multiple attribute in the xpath expression Ans:

Yes

Example:1) //input[@placeholder=’Username’ AND@name=’username’]

//input[@placeholder=’Username’ OR name=’username’]

2)//input[@value=’Log In’]

3)//input[@id=’next’]

4)//input[@value=’Next’]

4.Xpath by text():
If attribute is not present (or) attribute is matching with multiple elements in such cases we can use
xpath by text,which has following syntax:
//tag[text()=’textvalue’]

Example: 1)//div[text()=’Login’]

2)//div[text()=’USERS’]

NOTE: In the same xpath expression we can specify both attribute and text()

HANDLING NON-BREAKABLE SPACE:

1)developer can give the space in the value using spacebar or using Keyword &nbsp[non breakable space]

18
2)when we inspect the element in the browser we cannot make out whether &nbsp is used or not

3)If value has &nbsp then xpath will not identify such elements
Example:

<html>

<body>

<button type=”submit>&nbspOK&nbsp</button>

</body>

</html>

IN FIREBUG:

*<button type=”submit”> OK </button> not identify the element

*//button[text()=’ OK ‘] not identify the element To

handle non breakable space we should use contains() which has following syntax:

//tag[contains(text(),’textvalue’)]

//tag[contains(@AttributeName,’AttributeValue’)]

Example:

1) attribute example
button[contains(text(),’OK’)]

Example: //input[contains(@value,’Create Type of Work’)]login to actitime>settings>types of


work>create types of work> create types of work>

2)text example
//a[contains(text(),’delete’)]

19
NOTE:

We use contains() if value has non-breakable space or if value is keep changing.

Example://span[contains(text(),’Inbox’)]

XPATH TRAVERSING

We can derive a xpath expression which can navigate from one element to another element which is
called as traversing.It supports 2 types of traversing;

1) Forward Traversing

2) Backward Traversing

EXAMPLE:

<html>

<body>

<table border=”1”>

<tbody>

<tr>

<td>1</td>

<td>Unix</td>

<td>300</td>

</tr>

<tr>

<td>2</td>

<td>Java</td>

<td>400</td>

</tr>

</tbody>

</table>

</body>

</html>

1) FORWARD TRAVERSING:

20
Navigating from parent element to any of its child element is called as forward traversing.

Example:

Navigating from;

table to Unix;

//table/tbody/tr[1]/td[2]

Table to java;

//table/tbody/tr[2]/td[2]

2) BACKWARD TRAVERSING:

Navigating from child element to any of its parent element is called as backward traversing

Example:

Navigating from;

Unix to table;

//td[text()=’Unix’]/../../..

Java to table;

//td[text()=’Java’]/../../..

5) INDEPENDENT DEPENDENT XPATH:


If the element is completely changing (or) it duplicate with some other elements we can use
independent dependent concept of xpath to identify it.

EXAMPLE:

Derive xpath to identify cost of UNIX

Step#1:Inspect the independent element and Note down its source code.

Step#2:Place the mouse pointer on the source code of independent element and move the mouse pointer in
upward direction step by step till it highlights both independent and dependent element. This will be the common
parent ,add it to the html tree

Step#3:

Use arrow key to navigate till dependent element, add its path to the html tree.

Step#4:Using the tree derive the xpath expression which navigates from independent element to common
parent and then to dependent element

21
<tr>

<td>Unix</td> td<td[3]

//td[text()=’Unix’]/../td[3]

NOTE:

While doing forward traversing we should navigate till end i.e, expand all the + sign.

IQ2)Derive the xpath to match with download link of ruby present in download page of selenium

Ans:

tr

<td>ruby</td> td[4]

//td[text()=’Ruby’]/../td[4]/a

Note :

The above xpath identifies the link which is present in 4th column only.To identify the download link
even if column is keep changing we can use below xpath;

//td[text()=’Ruby’]/..//a[text()=’Download’]

Example in actiTime: //a[text()='Vidya']/../..//a[text()='set by default']

Assignment:

1) Derive a xpath to identify the price of Mi 4i(Blue 16GB) present in flipkart


//span[text()=' Rs. 11,998']
2) Derive a xpath to identify add to compare checkbox of Redmi2 Prime(Grey 16 GB) in flipkart
//input[@id='MOBE9T7GTHERTDAC']

3) Derive a xpath to identify phone number of Mumbai present in isrtc.com

4) Identify help icon(?) present in actitime application;


(//div[@class=’popup menu arrow’])[3]

Note:

Sometimes we may not be able to identify the element even after using all types of xpath which is
previously discussed.In such case we use GROUP INDEX(GI)

22
tbody

tr
td(SQL)

td(300)

tr
td(Java)

td(400)

*//td[1]->SQL

*(//td)[1]->SQL

*(//td)[3]->Java

*(//td[1])[2]->java

IQ3)What is the difference between //a, //a[1], (//a)[1] 1.all

the links

2.all the first links

3.only first link

IQ4)Derive the xpath which matches with last checkbox.

Answer: (//input[@type=’checkbox’])[last()]

IQ5)Write a xpath to select first and last checkbox

(//input[@type=’checkbox’])[1]|(//input[@type=’checkbox’])[last()]

|||ly

*(//input[@type=’checkbox’]

*(//input[@type=’checkbox’])[1]

*(//input[@type=’checkbox’])[6]

23
IMPORTANT LOCATORS:

1) Id

2) name

3) linkText

4) xpath
Note:

In very few situations xpath written using a browser(Firefox)may not work in some other browser,in such
cases we can use CssSelector.

CONVERTING XPATH TO CSSSELECTOR:

XPATH CSSSELECTOR
1) //button[@type=’submit’] button[type=’submit’]
2) //input[@id=’UN’] input#UN
3) //input[@class=’c1’] input.c1
4) //a a
5) //tr/td tr>td
6) //table//a table a

7) //td/.. Backward traversing is not supported in selenium


8) //td[text()=’Java’] text() is not supported in selenium

IQ6) Can we use independent dependent concept in selenium Ans;

No,because backward traversing is not supported in selenium

Note: 1) get() will enter the Url and wait till the page is completely loaded.Waiting time of get() is
infinite.

2)findElement() will search for specified element in the current page,if it is present it will returns
the address of the element.If it is not there it will trow NoSuchElementFoundException IMMEDIATELY.

SYNCHRONIZATION:

Process of matching Selenium speed with application is called as synchronization .In order to
synchronize the script we can use sleep() of Thread class as shown below;

24
Try

Thread.sleep(30000);

catch(InterruptedException e)

IMPLICITLY WAIT:
If we use sleep(),It will drastically increase maintenance consumes lot of time and space.Instead of this
we can use implicitly wait statement of selenium.

Example: driver.manage().timeouts.implicitlyWait(30,TimeUnit.SECONDS);

In the above example 30SECONDS is used by all the findElement method and each findElement() waits
upto 30 SECONDS.

After every half second it will search for element in page till the time out or till the element is located
which ever comes earlier,This is called POLLING PERIOD.This is specified in a class called FluentWait.

The implicitelyWait() takes 2 arguments i.e,duration(long type) and Timeunit() such as


DAYS,HOURS,SECONDS,MINUTES,MILLISECONDS,MICROSECONDS and NANOSECONDS

If element is not located even after the time out then FindElement() will throw
NoSuchElementException

EXPLICIT WAIT:
*If the method is other than findElement then to synchronize it we can use explicit wait.

*webDriverWait itself is called as Explicitwait because we specify waiting condition Explicitly These

conditions are available in ExpectedConditions class,these are also called as Predicates.

*If specified condition is not specified even after the specified duration then explicitWait will throw
TimeoutException(Selenium unchecked exception)

Code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

25

You might also like