Você está na página 1de 25

Selenium Xpath Tutorials

Identifying xpath for element with examples to use in selenium


QA Engineers need to provide any element locator(like id, name, css path,
xpath etc.) in target column of selenium window to locate that specific element
to perform some action on it .If you have worked with selenium IDE then you
knows that sometimes elements does not contains id or name. Locating
element by xpath is the another way of locating element and you can use it as
a alternative of id or name of element.
Xpath in XML document shows the direction of element location through nodes
and attributes. Let we try to understand how to identify Xpath of element with
examples.

Above given image is taken from http://www.wikipedia.org/. There are three


fields 1. Input text box 2. Select drop
down and 3. Input button. And bellow
Comma
of those fields there is expansion of
Target
Value
relative XML nodes through firebug. As nd
you see in image, you can use
"id=searchInput" or "name=search" to
http://www.wikiped
Open
identify input text box to type
ia.org
something in to it as bellow given
example.
Seleniu
m
Type
name=search
Comma
Automat
Target
Value
nd
ion

Open

Type

http://www.wikiped
ia.org

id=searchInput

Seleniu
m
Automat
ion

Xpath Element Identification


Locating element using Xpath with Examples for input text box
Xpath
Techniq Examples
ues

Explanations

//body is the
main root
node, /div[3]
describes the
3rd div child
node of parent
node body,
/form
Identifyi
describes the
ng
child node
Xpath
xpath=//body/div[3]/form/fieldset/in form of parent
1
using
put[2]
node div[3],
full path
/fieldset
of XML
describes the
child node
fieldset of
parent node
form, /input[2]
describes the
2nd input child
node of parent
node fieldset.
/input[last()-2]
describes the
Writting
3rd upper
Xpath
xpath=//body/div[3]/form/fieldset/in
2
input
using
put[last()-2]
node(input[2])
last()
from last input
node.
/*[last()-3]
Writting
describes the
Xpath
xpath=//body/div[3]/form/fieldset/*[l
3
4th upper
using
ast()-3]
node(input[2])
last()
from last node.
4 Xpath

xpath=//body/div[3]/form/fieldset/in /

locator
using @
and
put[@type='search']
attribut
e

input[@type='s
earch']
describes the
input node
having
attribute
type='search'

/
input[@access
Xpath
key='F']
expressi
describes the
on using xpath=//body/div[3]/form/fieldset/in
5
input node
@ and
put[@accesskey='F']
having
attribut
attribute
e
@accesskey='F
'

Xpath
syntax
using @
6
xpath=//input[@accesskey='F']
and
attribut
e

//input[@acces
skey='F']
describes the
input node
having
attribute
@accesskey='F
'

Xpath
example
using @
7
xpath=//input[@type='search']
and
attribut
e

/
input[@type='s
earch']
describes the
input node
having
attribute
type='search'

In this case ,
only starting
node div with
attribute
XML
class='searchXpath
container' and
xpath=//div[@class='searchusing
final node
8
container']/descendant::input[@acce
/descen
input with
sskey='F']
dant::
accesskey='F'
keyword
attribute. So
not need to
describe in
between
nodes.
9 Xpath
xpath=//input[contains(@id,
query
"searchInput")]
example
using
contains

used contains
keyword to
identify id
attribute with
text

keyword

"searchInput"

Xpath
using
xpath=//input[contains(@id,
1
and with "searchInput") and
0
attribut contains(@accesskey,"F")]
es

two attributes
in input node

XML
xpath
value
xpath=//div[@class='search1
value
container']/descendant::input[positi
1
using
on()=2]
position
()

This xpath will


select input
node which is
on number 2
position and it
is for input
text box as
shown in
image.

Using
1 starts- xpath=//input[starts-with(@type,
2 with
"s")]
keyword

ind input node


with attribute
is 'type' and its
value is
starting with
's' (here it will
get type =
'search').

Using
OR (|)
conditio
n with
xpath

xpath=//input[@accesskey='F'] |
//input[@id='searchInput']
xpath=//input[@accesskey='F' or
@id='searchInput']

Using
wildcard
1 * with to
xpath=//*[@accesskey='F']
3 finding
element
xpath
1 Finding xpath=//body/*[3]/form/fieldset/*[2]
4 nth child
element
of
parent

it will find
input text box
with
accesskey='F'
or
@id='searchIn
put'. If any one
found then it
will locate it.
Very useful
when elements
appears
alternatively.

This finds any


element that
has accessKey
attribute="F"

Here, /*[3]
describes the
3rd child
element of
body which is
div[3]. Same
way *[2]
describes the

2nd child
element of
fieldset which
is input[2]
Using
1 Text() to
xpath=//div/a[text()="English"]
5 find
element

This will find a


link that has
text ="English"

Xpath examples for drop down


1. xpath=//body/div[3]/form/fieldset/select
2. xpath=//body/div[3]/form/fieldset/select[last()]
3.
xpath=//body/div[3]/form/fieldset/select[@id='searchLanguage'
]
4. xpath=//body/div[3]/form/fieldset/select[@name='language']
5. xpath=//div[@class='searchcontainer']/descendant::select[@name='language']
6. xpath=//select[contains(@id, "searchLanguage")]
7. xpath=//div[@class='searchcontainer']/descendant::select[position()=1]
8. xpath=//body/div[3]/form/fieldset/select[count(*)>1]

Other Xpath Example


1. Finding xpath in selenium for target link 'url'
//a[@href='//meta.wikimedia.org/wiki/List_of_Wikipedias'] ////This xpath
example will find link with given URL
(//meta.wikimedia.org/wiki/List_of_Wikipedias) on the page.

2. Finding xpath of element with no child


xpath=//img[count(*)=0] ////This xpath is for wikipedia text logo which is
display on top of the page. This xpath will find that image element which have
not any child element. Here image node is last and it has not any child
element.

xpath=//div[2]/descendant::img[count(*)=0]
logo image which is display under logo text.

//// This xpath is for wikipedia

- See more at: http://www.software-testing-tutorialsautomation.com/2013/06/xpath-tutorials-identifying-xpathfor.html#sthash.x5MPJXm5.dpuf

Top 20 Useful Commands in Selenium Webdriver.

1. Creating New Instance Of Firefox Driver


WebDriver driver = new FirefoxDriver();
Above given syntax will create new instance of Firefox driver.
2. Command To Open URL In Browser
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
This syntax will open specified URL in web browser.
3. Clicking on any element or button of webpage
driver.findElement(By.id("submitButton")).click();
Above given syntax will click on targeted element in webdriver.
4. Store text of targeted element in variable
String dropdown = driver.findElement(By.tagName("select")).getText();
This syntax will retrieve text from targeted element and will store it in variable =
dropdown.
5. Typing text in text box or text area.
driver.findElement(By.name("fname")).sendKeys("My First Name");
Above syntax will type specified text in targeted element.
6. Applying Implicit wait in webdriver
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
This syntax will force webdriver to wait for 15 second if element not found on page.
7. Applying Explicit wait in webdriver with WebDriver canned conditions.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id='ti
meLeft']"), "Time left: 7 seconds"));
Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7 seconds" to be
appear on targeted element.
8. Get page title in selenium webdriver
driver.getTitle();
It will retrieve page title and you can store it in variable to use in next steps.
9. Get Current Page URL In Selenium WebDriver
driver.getCurrentUrl();
It will retrieve current page URL and you can use it to compare with your expected URL.
10. Get domain name using java script executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return document.domain");
Above syntax will retrieve your software application's domain name using webdriver's
java script executor interface and store it in to variable.
11. Generate alert using webdriver's java script executor interface
JavascriptExecutor javascript = (JavascriptExecutor) driver;

javascript.executeScript("alert('Test Case Execution Is started Now..');");


It will generate alert during your selenium webdriver test case execution.
12. Selecting or Deselecting value from drop down in selenium webdriver.
Select By Visible Text
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
It will select value from drop down list using visible text value = "Audi".
Select By Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
It will select value by value = "Italy".
Select By Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
It will select value by index= 0(First option).
Deselect by Visible Text
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");
It will deselect option by visible text = Russia from list box.
Deselect by Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");
It will deselect option by value = Mexico from list box.
Deselect by Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
It will deselect option by Index = 5 from list box.
Deselect All
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
It will remove all selections from list box.
isMultiple()
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
It will return true if select box is multiselect else it will return false.
13. Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step back and 3rd
command will
14. Verify Element Present in Selenium WebDriver
Boolean iselementpresent = driver.findElements(By.xpath("//input[@id='text2']")).size()!
= 0;
It will return true if element is present on page, else it will return false in variable
iselementpresent.
15. Capturing entire page screenshot in Selenium WebDriver
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));


It will capture page screenshot and store it in your D: drive.
16. Generating Mouse Hover Event In WebDriver
Actions actions = new Actions(driver);
WebElement moveonmenu = driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();
Above example will move mouse on targeted element.
17. Handling Multiple Windows In Selenium WebDriver.
1. Get All Window Handles.
Set<String> AllWindowHandles = driver.getWindowHandles();
2. Extract parent and child window handle from all window handles.
String window1 = (String) AllWindowHandles.toArray()[0];
String window2 = (String) AllWindowHandles.toArray()[1];
3. Use window handle to switch from one window to other window.
driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to switch from one
window to another window
18. Check Whether Element is Enabled Or Disabled In Selenium Web driver.
boolean fname = driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not. You can use it
for any input element.
19. Enable/Disable Textbox During Selenium Webdriver Test Case Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')[0].setAttribute('disabled',
'');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname')
[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
It will disable fname element using setAttribute() method and enable lname element
using removeAttribute() method.
20. Selenium WebDriver Assertions With TestNG Framework
assertEquals
Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal values.
assertNotEquals
Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values.
assertTrue
Assert.assertTrue(condition);
assertTrue assertion works for boolean value true assertion.
assertFalse
Assert.assertFalse(condition);
How to execute selenium webdriver tes script parallel in multiple browser
using testng parameter annotation.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowser {
private WebDriver driver;
@Parameters("browser")
@BeforeMethod
public void setup(String browser)
{
if(browser.equalsIgnoreCase("firefox"))
{
driver = new FirefoxDriver();
}
else if(browser.equalsIgnoreCase("iexplorer"))
{
// Update the driver path with your location
System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
else if(browser.equalsIgnoreCase("chrome"))
{
// Update the driver path with your location
System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
driver.manage().window().maximize();
}
@AfterMethod
public void tearDown()
{
driver.quit();
}
@Test
public void testMultiBrowser() throws InterruptedException
{
driver.get("http://www.google.com");
Thread.sleep(3000);
}
}
2. Now we need to create TestNG.xml and write the following code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MultiBrowser">
<test name="TestFirefox" verbose="10">
<parameter name="browser" value="firefox" />
<classes>
<class name="MultiBrowser" />
</classes>

</test>
<test name="ChromeTest">
<parameter name="browser" value="chrome" />
<classes>
<class name="MultiBrowser" />
</classes>
</test>
<test name="IETest">
<parameter name="browser" value="iexplorer" />
<classes>
<class name="MultiBrowser" />
</classes>
</test>
</suite>
3. Now run the code from TestNG.xml
You can observer all the three browsers will open and perform the task at a time.

Selenium WebDriver methods with Examples


Selenium WebDriver methods with Examples

1.Browser Back and Forward (NAVIGATION)


Steps to implement Browser back and forward through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Navigate to some page in website.
4. Use Selenium code to Navigate Back to Main Page.
CODE: driver.navigate().back();
driver.navigate().forward();
Example
WebDriver driver =new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000);
//delay
driver.navigate().back();
driver.navigate().forward();
------------------------------------------------------------------------------------------------------------------------------

2.Handling DRAG and DROP


Steps to Handle Drag and Drop through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Create an Action object for Driver
4. Fetch and create WebElement object for the SOURCE element.
5. Fetch and create WebElement object for the DESTINATION element.
6.Perform ACTION
1.Click and Hold the source WebElement
2.Move to destination WebElement
3.Release the Element.
Example
WebDriver driver = new FirefoxDriver();
driver.get("http://www.ericbieller.com/examples/dragdrop/");

driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
Actions act = new Actions(driver);
WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement des = driver.findElement(By.id("trash"));
act.clickAndHold(src).build().perform();
//For each action we need to build and Perform
act.moveToElement(des).build().perform();
act.release(des).build().perform();-----------------------------------------------------------------------------------------------------------------------------

3.Making Single Select in Drop down (Option List)


Steps to make Single Select in Drop down through Selenium Web Driver.
1.
2.
3.
4.
5.
6.
7.
8.

Create Driver for any Browser(Mozilla)


Go to the URL
Fetch the Drop Down element and create an object as WebElement.
Create an Select object for the Drop Down Element object.
Create a List and collect all Options through Select Object.
Create a Iterator object for the List.
Get the size of the List.
Loop through and check for required element.

Example
WebElement element = driver.findElement(By.name("selectedCustomer"));
Select dd= new Select(element);
List allOptions= dd.getOptions();
//To go through the list, we can use an Iterator.
//Iterator should be of the same type as the List
//which is WebElement in this case.
Iterator it = allOptions.iterator();
//Using while loop, we can iterate till the List has
//a next WebElement [hasNext() is true]
//number of items in the list
System.out.println(allOptions.size());
while(it.hasNext()){
//When you say it.next(), it points to a particular
//WebElement in the List.
WebElement el = it.next();
//Check for the required element by Text and click it
if(el.getText().equals("mango")){
System.out.println(el.getAttribute("value"));
el.click();
}
}
------------------------------------------------------------------------------------------------------------------------------

4.Making Single Select in Drop down (By INDEX, VALUE, TEXT)


Steps to make Single Select in Drop down through Selenium Web Driver.
1.
2.
3.
4.
5.
6.
7.

Create Driver for any Browser(Mozilla)


Go to the URL
Fetch the Drop Down element and create an object as WebElement.
Convert the Drop Down Element in to Select object.
Select by INDEX
Select by VALUE
Select by VISIBLE TEXT

Example

WebElement customerdd = driver.findElement(By.name("customerProject.shownCustomer"));


//convert the element to select object
Select cust = new Select(customerdd);
cust.selectByIndex(1);
//Select by Index
Thread.sleep(3000);
cust.selectByValue("2");
//Select by Value
Thread.sleep(3000);
cust.selectByVisibleText("mango");
//Select by Visible Text
------------------------------------------------------------------------------------------------------------------------------

5.Multiple Select List Box Window


Steps to make Multiple Select in Drop down through Selenium Web Driver.
1.
2.
3.
4.
5.
6.

Create Driver for any Browser(Mozilla)


Go to the URL
Fetch the Drop Down element and create an object as WebElement.
Convert the Drop Down Element in to Select object.
Select by Index(Start index)
Select by Index(End index)

Example

WebElement userdd = driver.findElement(By.name("users"));


Select usr = new Select(userdd);
usr.selectByIndex(0);
//Select by Index(From Start location)
usr.selectByIndex(2);
//Select by index(To End Location)
------------------------------------------------------------------------------------------------------------------------------

6.Multiple Select List Box Window - DESELECT


Steps to make Deselect in Drop down through Selenium Web Driver.
1.
2.
3.
4.
5.
6.

Create Driver for any Browser(Mozilla)


Go to the URL
Fetch the Drop Down element and create an object as WebElement.
Convert the Drop Down Element in to Select object.
Select by Index(Start index)
Select by Index(End index)

Example
WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);
usr.selectByIndex(2);

//You can deselect the options


usr.deselectAll();
//or

//Deselect ALL selected elements

usr.deselectByIndex(0);
//Deselect By using Index
//or
usr.deselectByValue(value);
//Deselect By using Value
//or
usr.deselectByVisibleText(text);
//Deselect By using Text
------------------------------------------------------------------------------------------------------------------------------

7.iFRAMES - How to handle Frames in Web Driver


Steps to get Source of each iFrame through Selenium Web Driver.
1.
2.
3.
4.
5.

Create Driver for any Browser(Mozilla)


Go to the URL
Make a List containing FRAME web elements of a Web Page.
Get the Size of Frames.
Loop though and print the Source of each Frame

Example

/*times of india website - multiple frames*/


driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List frms= driver.findElements(By.tagName("iframe")); //Frame List
System.out.println(frms.size());
for(int i=0;i
{
System.out.println(frms.get(i).getAttribute("src"));
}------------------------------------------------------------------------------------------------------------------------------

8.iFRAMES - How to perform action in Frames


Steps to perform Action in iFrame through Selenium Web Driver.
1.
2.
3.
4.
5.

Create Driver for any Browser(Mozilla)


Go to the URL
Fetch iFrame element and create an Web Element object.
Using iFrame Web Element object, switch to IFrame.
Perform SendKeys/ Click action in iFrame.

Example

WebElement ifr = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));


driver.switchTo().frame(ifr);
//Switch to iFrame
driver.findElement(By.id("mathuserans2")).sendKeys("8"); //Perform Action in iFrame
------------------------------------------------------------------------------------------------------------------------------

9.iFRAMES - How to switch to a perticular Frame through index


Steps to switch to perticular iFrame by index through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)

2.
3.
4.
5.

Go to the URL
Make a List containing FRAME web elements of a Web Page.
Get the Size of Frames.
Switch to required iFrame through index.

Example
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List frms= driver.findElements(By.tagName("iframe"));
System.out.println(frms.size());
driver.switchTo().frame(0);
driver.findElement(By.id("clicktripad")).click();
------------------------------------------------------------------------------------------------------------------------------

10. TABS / New Window


When Browser opens in a new window or in a new tab, Web Driver cannot shift the control to the
new Window/ Tab. We need to collect the window handles in a page. Whenever a new window
opens we need to iterate and shift to the latest window handle.
TABS/New Window - 1
Steps to iterate through the Window Handles
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. At First iterator will not be pointing to any Window Handle, only First increment Points to First
Window Handle, Second increment Points to second iterator.

Set windowHandles = driver.getWindowHandles();


Iterator it = windowHandles.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}-----------------------------------------------------------------------------------------------------------------------------TABS/New Window - 2
When two browsers are opened and Web Driver need to shift the control from Parent Window to
Child Window.
Please follow the steps mentioned below.

1.
2.
3.
4.
5.
6.
7.

Create Driver for any Browser(Mozilla)


Go to the URL
Collect Window Handles through Set
Create an iterator to iterate through Window Handles.
Increment the iterator and store the Window Handle as Parent.
Increment the iterator and store next Window Handle as Child.
Switch to Child Browser using Child Window Handle.

Set windowHandles = driver.getWindowHandles();


Iterator it = windowHandles.iterator();

String parentBrowser= it.next();


String childBrowser = it.next();
driver.switchTo().window(childBrowser);
------------------------------------------------------------------------------------------------------------------------------

TABS/New Window - 3
When second browser is closed/you close it and Web Driver need to shift the control from Child
Window to Parent Window.
Please follow the steps mentioned below.

1.
2.
3.
4.
5.
6.
7.
8.

Create Driver for any Browser(Mozilla)


Go to the URL
Collect Window Handles through Set
Create an iterator to iterate through Window Handles.
Increment the iterator and store the Window Handle as Parent.
Increment the iterator and store next Window Handle as Child.
Switch to Child Browser using Child Window Handle.
When Child browser get closed, Switch from Child browser to Parent Window.

Set windowHandles = driver.getWindowHandles();


Iterator it = windowHandles.iterator();
String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);
Thread.sleep(3000);
driver.close();
//close the current window(Child Browser)
driver.switchTo().window(parentBrowser);
//Switch to Parent Browser

------------------------------------------------------------------------------------------------------------------------------

11. CALENDAR popups


Calendar PopUp - 1
Normal Calender(current month) Popup can be handled in the following way.
1.
2.
3.
4.

Create Driver for any Browser(Mozilla)


Go to the URL
Fetch the Calender element and click to open.
Fetch the required date through xpath and click.

/*IRCTC calendar*/
driver.findElement(By.id("calendar_icon1")).click();
driver.findElement(By.xpath("//div[@id='CalendarControl']/table[tbody[tr[td[text()='October
2012']]]]/descendant::a[text()='5']")).click();
-----------------------------------------------------------------------------------------------------------------------------Calendar PopUp - 2 (Customized wait)
In a Calender if we want to click on future month which is not currently displayed, we need to
click on next link until we get the required month.
This can be done by writing Customized wait. Check for particular date element in each
month, if not found move to next month.
/*makemytrip calendar*/
driver.get("http://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("deptDateRtripimgExact")).click(); //find Calendar
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
boolean flag=true;
while(flag){
try {
WebElement el = driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-group') and
descendant::span[text()='March']]/descendant::a[text()='5']")); // Required future date
if(el !=null) //Check if the required date element is found or not
{
el.click(); // if required Date is found, then click the date
flag=false;
}
}
catch (Exception e) { //Catches exception if no element found
try {
Thread.sleep(500);
driver.findElement(By.xpath("//a[@title='Next']")).click(); //Click on next month
}
catch (InterruptedException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------------------------------------

12. Drop Down MENU

In order to click on an menu item, first we need to move the mouse over Parent menu, later we
can click on any of the Menu child item.
Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)

2.
3.
4.
5.
6.
7.

Go to the URL
Fetch the MENU Parent element and create a WebElement object.
Create an Action object for Driver
Through Action object, move to Parent element.
Give a Delay for menu items to be displayed.
Fetch the Child item through xpath and Click on it.

WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));


Actions act = new Actions(driver); // Create an Action object
//move to the parent menu item
act.moveToElement(parentMenu).build().perform();
Thread.sleep(3000); //wait till the child items are displayed
driver.findElement(By.linkText("Bharat Tirth")).click();
------------------------------------------------------------------------------------------------------------------------------

13. Context Click (Right Click)


We can use keyboard keys to Make a Right Click.
Please follow the steps mentioned below.

1.
2.
3.
4.
5.
6.

Create Driver for any Browser(Mozilla).


Go to the URL.
Fetch the MENU Parent element and create a WebElement object.
Create an Action Object for Driver.
Through Action Object, make a Context Click on Menu Parent object.
Through Action Object, send keys for ARROW_DOWN/ARROW_UP/Keys.ENTER.

Example
WebElement parentMenu = driver.findElement(By.linkText("Tourist Trains"));
Actions act = new Actions(driver); //Create Action object for Driver
act.contextClick(parentMenu).build().perform(); //Context Click
act.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform();
------------------------------------------------------------------------------------------------------------------------------

14. JAVA SCRIPT example


We can use java script command to perform actions.
We can write code to fill up the text box through java script.
Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).

2.
3.
4.
5.

Go to the URL.
Create Java Script executor object for the Driver.
Store the Java Script command in a String Variable.
Java Script Executor object executes the command in the Variable.

JavascriptExecutor js = (JavascriptExecutor) driver;


String jsCmd = "document.getElementsByName('city')[0].value='ban'";
js.executeScript(jsCmd);
------------------------------------------------------------------------------------------------------------------------------

15. Multiple Elements


We can count the number of links present in the page. We can also print the link text of each Web
link.

Please follow the steps mentioned below.


1.
2.
3.
4.
5.

Create Driver for any Browser(Mozilla).


Go to the URL.
Fetch elements with tag //a in the entire page, store it in a List.
Get the count of Links present in the Page.
Loop through the links and print the Attributes

List allLinks= driver.findElements(By.xpath("//a"));


//display the count of links in the page
System.out.println(allLinks.size());
//display the text for each link on the page
for(int i=0;i
{
//display href for each link
System.out.println(allLinks.get(i).getAttribute("href"));
//display text for each link
System.out.println(allLinks.get(i).getText());
//perform click action
allLinks.get(i).click();
}
-----------------------------------------------------------------------------------------------------------------------------16. Other Browser (Internet Explorer)

Using Internet Explorer with Web Driver.


Please follow the steps mentioned below.
1. Set System Property for the Driver and give path of the IE Driver.
2. Create an Web Driver Object.
3. Open an URL

System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");

WebDriver driver =new InternetExplorerDriver();


driver.get("www.google.com");
------------------------------------------------------------------------------------------------------------------------------

17. Other Browser (Chrome)


Using Chrome with Web Driver.
Please follow the steps mentioned below.
1. Set System Property for the Driver and give path of the Chrome Driver.
2. Create an Web Driver Object.
3. Open an URL

System.setProperty("webdriver.chrome.driver", "D:\\sel\\browserdrivers\\Chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("www.google.com");
------------------------------------------------------------------------------------------------------------------------------

18. PROXY settings.


Please follow the steps mentioned below.
1.
2.
3.
4.
5.
6.
7.

Import Selenium.Proxy
Create a Profile object for Firefox
Create a string variable with value.
Create a Proxy object.
Set the values through proxy.
Set the proxy preference to proxy object using profile object.
Pass the profile object to Firefox Driver.

import org.openqa.Selenium.Proxy
FirefoxProfile profile = new FirefoxProfile();
String PROXY = "xx.xx.xx.xx:xx";
Proxy proxy = new Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);

------------------------------------------------------------------------------------------------------------------------------

19. Page Onload authentication

Sometimes when you are Automating Web pages, you may come across Page onload
Authentication window. This window is not java popup/div. It is windows popup. Selenium directly
cannot handle this windows popup.
Hence we use Autoit sowftware tool. Through Selenium we can handle this situation using Autoit.
Please follow the steps mentioned below.
1.Download Autoit from the following URl
( http://www.autoitscript.com/site/autoit/downloads/ )
2.Install downloaded software.
3. Open Script Editor
Start=>ProgramFiles=>AutoIt =>SciTE Script Editor.
4.Open Object Identifier.
Start=>ProgramFiles=>AutoIt =>AutoIt Window Info.
5.Drag and Drop finder tool in AutoIt Window Info, to the Window you need to
identify.
6.Collect the Title Name of window from (AutoIt Window Info.)
7.Write the Script in the Editor.
----------------------------------------------------AUTOIT CODE----------------------------------------------------WinWaitActive("Authentication Required")
Send("admin")
Send("{TAB} admin{TAB} {ENTER}")
-----------------------------------------------------------------------------------------------------------------------------8.Save the file as default save.(Authentication1.exe)
9.RUN/Compile the SCRIPT, it creates an exe.
10.Mention the exe path in the Program before creation of Driver.
EXAMPLE:

Process P = Runtime.getRuntime().exec("D:\\java_prj\\SELENIUM WEBDRIVER\\AUTOIT\\Authentication1.exe");


WebDriver driver = new FirefoxDriver();
driver.get("http://192.168.1.1");
------------------------------------------------------------------------------------------------------------------------------

20. File Download


Please follow the steps mentioned below.

1. Create a PROFILE object of Browser.


2. Set Preference, by giving Download destination Directory.
3. Set Preference, by giving Default Folder. 0 => Desktop, 1=>System Default Location, 2 =>
Indicates a custom Folder Location
4. Set Preference, A comma-separated list of MIME types to save to disk without asking what to
use to open the file. Default value is an empty string.
After coding the above mentioned steps, now start the driver and click on Download button/link.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the Download web element and click.

FirefoxProfile Prof = new FirefoxProfile();


Prof.setPreference("browser.download.dir", "D:\\java prj");

Prof.setPreference("browser.download.folderList", 2);
Prof.setPreference("browser.helperApps.neverAsk.saveToDisk","application/zip");
WebDriver driver = new FirefoxDriver(Prof);
driver.get("http://seleniumhq.org/download/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
driver.findElement(By.xpath("//a[@name='client-drivers']/table/tbody/tr[1]/td[4]/a")).click();
------------------------------------------------------------------------------------------------------------------------------

21. File Upload


Please follow the steps mentioned below.

1.
2.
3.
4.
5.

Create Driver for any Browser(Mozilla).


Go to the URL.
Store the Source path of file in a variable.
Fetch the Upload web element text box and give path using variable.
Fetch the upload button and click

WebDriver driver = new FirefoxDriver();


driver.get("http://www.2shared.com/");
String FilePath = "C:\\Users\\abc\\Desktop\\test.xml";
driver.findElement(By.id("upField")).sendKeys(FilePath);
driver.findElement(By.xpath("//input[@type='image']")).click();
------------------------------------------------------------------------------------------------------------------------------

22. Handling JAVA ALERT


Sometimes you may get alerts as anticipated(through Insert/update/delete operation in database).
These may be JAVA alerts.
Please follow the steps mentioned below to handle Alerts.

1.
2.
3.
4.
5.
6.

Create Driver for any Browser(Mozilla).


Go to the URL.
You get an alert asking to click on 'YES' or 'NO' button.
First Confirm if it is JAVA alert window.
Write a code to switch the control to Alert window.
In the Alert window, either ACCEPT by clicking on 'YES'
or CANCEL by clicking on 'NO'.

WebDriver driver = new FirefoxDriver();


driver.get("http://www.2shared.com/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
Alert alert = driver.switchTo().alert();
alert.accept();
//or
alert.dismiss();

WebDriver with TestNG - Gmail Login Functionality


Below is the code for GMAIL Login functionality using WebDriver with TestNG
package com.test.webdriver;
import static org.testng.AssertJUnit.assertEquals;

import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.firefox.FirefoxDriver;
org.testng.annotations.AfterClass;
org.testng.annotations.BeforeClass;
org.testng.annotations.Test;

public class Driver {


private WebDriver driver;
@BeforeClass
public void Startup(){
driver = new FirefoxDriver();
}
@Test (description="Google Login")
public void GoogleLogin() throws Exception{
driver.get("http://www.gmail.com");
assertEquals("Sign in", driver.findElement(By.id("signIn")).getAttribute("value"));
driver.findElement(By.id("Email")).sendKeys("*********");
driver.findElement(By.id("Passwd")).sendKeys("**********");
driver.findElement(By.id("signIn")).click();
Thread.sleep(10000);
driver.switchTo().frame("canvas_frame");
driver.findElement(By.id("gbgs4dn")).click();
driver.findElement(By.id("gb_71")).click();
driver.switchTo().defaultContent();
assertEquals("Sign in to Gmail", driver.findElement(By.id("button")).getText());
}
@AfterClass
public void teardown(){
driver.quit();
}
}

using functions in xpath in selenium


How to use functions in xpath in selenium
Automation using selenium is a great experience. It provides many way to identif an object or element on
the web page.But sometime we face the problems of idenfying the objects on a page which have same
attributes. When we get more than one element which are same in attribute and name like multiple
checkboxes with same name and same id. More than one button having same name and ids. There are no
way to distingues those element. In this case we have problem to instruct selenium to identify a perticular
object on a web page.
I am giving you a simple example . In the below html source there are 6 checkboxes are there having same
type and same name.
It is really tough to select third or fifth.
input type='checkbox' name='chk' first
input type='checkbox' name='chk' second
input type='checkbox' name='chk' third
input type='checkbox' name='chk' forth
input type='checkbox' name='chk' fifth
input type='checkbox' name='chk' sixth
Thare are some function we can use in Xpath to identify the abject in above cases. An XPath expression
can return one of four basic XPath data types:
* String
* Number
* Boolean

* Node-set
XPath Type : Functions
Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()
String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), stringlength(), normalize-space(), translate()
Boolean : boolean(), not(), true(), false(), lang()
Number : number(), sum(), floor(), ceiling(), round()
I will show you how we can use some of these above functions in xpath to identify the objects.
Node Set : last()
In the above html file there are six checkboxes and all are having same attributes (same type and name)
How we can select the last checkbox based on the position. We can use last() function to indentify the last
object among all similar objects.
Below code will check or uncheck the last checkbox.
selenium.click("xpath=(//input[@type='checkbox'])[last()]");
How we can select the second last checkbox and third last checkbox. We can use last()- function to
indentify the last object among all similar objects.
Below code will check or uncheck the second last checkbox and thrid last checkbox respectively.
selenium.click("xpath=(//input[@type='submit'])[last()-1]");
selenium.click("xpath=(//input[@type='submit'])[last()-2]");
Node Set : position()
If you want to select any object based on their position using xpath then you can use position() function in
xpath.
You want to select second checkbox and forth checkbox then use below command
selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");
selenium.click("xpath=(//input[@type='checkbox'])[position()=4]");
above code will select second and forth checkbox respectively.
String : starts-with()
Many web sites create dynamic element on their web pages where Ids of the elements gets generated
dynamically.
Each time id gets generated differently. So to handle this situation we use some JavaScript functions.
XPath: //button[starts-with(@id, 'continue-')]
Sometimes an element gets identfied by a value that could be surrounded by other text, then contains
function can be used.
To demonstrate, the element can be located based on the suggest class without having
to couple it with the top and business classes using the following
XPath: //input[contains(@class, 'suggest')].

Frequently asked questions on the Selenium 2 (Webdriver) Framework


Q. How to configure the framework in to eclipse?
A. Following are the steps to configure framework in eclipse:
Extract the provided zip folder
Open eclipse and create a new project using the extracted zip folder
Run the sample test script RegistrationTest.java by using the JUnit option
Create new test scripts in the folder 'TestScipts' and run them using JUnit option
Q. Does the framework work only for java language?
A. The framework is made in Java language but is language agnostic and can be used
with any language.
Q. What is meant by Page Object Model design?
A. Page Object Model is a simple design pattern that models each page (or page chunk)
as a class object that other classes / objects can interact with.
Q. Where can I see the generated reports?
A. We can see the HTML view of generated reports:

Run the build.xml as Ant Build


Refresh the project and open the Reports folder
From the Reports folder, open the index.html file with Web Browser
Q. How can I change the browser to be used for running the test scripts?
A. Following are the steps:
Go to the config folder
Open the gui_automation.properties file
Uncomment the needed browser configuration and comment the not needed
browser in this file and save the file
Q. Does WebDriver support file uploads?
A. Yes, it is possible if you call WebElement#sendKeys("/path/to/file") on a file upload
element. Make sure you don't use WebElement#click() on the file upload element or the
browser will hang.
Q. What input fields have been targeted in v3 of the framework using
parameterization
A. Text boxes, radio buttons, drop downs, check boxes, auto-suggest search drop down,
and file upload.
Q. How can I handle multiple windows?
A. You can handle multiple windows using the "WebDriver.switchTo().window()" method here window name is required. If the name is not known, you can use
"WebDriver.getWindowHandles()" to obtain a list of known windows and then switch to a
specific window.
Q. Can I make webdriver to wait for some event on default?
A. Yes.
Example: new
WebDriverWait(driver,20).until(ExpectedConditions.presenceOfElementLocated(B
y.id("loginBox")))
Q. Does the framework support the .xlsx extension files for parameterization?
A. Yes. We have provided support for .xlsx extension files i.e. 2007-2010 format, using
Apache POI.
Q. When I can use implicit and explicit wait?
A. Implicit wait will be used when you need to wait for all elements in script, while Explicit
wait method will be used only for particular specified elements. Explicit wait will be
preferred for dynamically loading ajax elements.
Implicit wait Example:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Wait Example:
public static WebElement explicitWait(WebDriver driver,By by){
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.presenceOfElementLocated(by)); }
Q. Which command should be used to quit WebDriver instance?
A. The quit() method is used to quit WebDriver instance. That is:
driver.quit();
Q. How can I drag element from one position and drop to second position?
A. This event can be implemented by using Action interface. Example:
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement).
moveToElement(otherElement).release(otherElement).build();
dragAndDrop.perform();
Q. How can I move backwards or forwards in browser's history in Webdriver?
A. You can move backwards and forwards in browsers history as below:
//To go backward
driver.navigate().back();
//To go forward
driver.navigate().forward();
Q. How can I get title of the window?
A. You can get the title of the window by using getTitle() method:
String title = driver.getTitle();
System.out.println("Title of the page is "+title);

Q. How to Maximize the browser to screen size?


A. To maximize the browser window to screen size Toolkit.getScreenSize() method is
used:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenResolution = new Dimension((int)
toolkit.getScreenSize().getWidth(), (int)
toolkit.getScreenSize().getHeight());
driver.manage().window().setSize(screenResolution);
Q. How to handle pageload time in webdriver?
A. You can set the PageLoadTimeout value to whatever you need using:
driver.Timeouts.PageLoadTimeout(XX, SECONDS)
where XX is the number of seconds you want the timeout to be set to.
Q. How can i get text from alert window ?
A. To get text from alert box, first you have to switch on alert, and then you can use
getText method:
Alert alert = driver.switchTo().alert();
// Get the text from the alert
String alertText = alert.getText();

Você também pode gostar