Top 20 Useful Commands in Selenium Webdriver
Top 20 Useful Commands in Selenium Webdriver
Open
Type
http://www.wikiped
ia.org
id=searchInput
Seleniu
m
Automat
ion
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
()
Using
1 starts- xpath=//input[starts-with(@type,
2 with
"s")]
keyword
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.
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
xpath=//div[2]/descendant::img[count(*)=0]
logo image which is display under logo text.
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.
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();-----------------------------------------------------------------------------------------------------------------------------
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();
}
}
------------------------------------------------------------------------------------------------------------------------------
Example
Example
Example
WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);
usr.selectByIndex(2);
usr.deselectByIndex(0);
//Deselect By using Index
//or
usr.deselectByValue(value);
//Deselect By using Value
//or
usr.deselectByVisibleText(text);
//Deselect By using Text
------------------------------------------------------------------------------------------------------------------------------
Example
Example
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();
------------------------------------------------------------------------------------------------------------------------------
1.
2.
3.
4.
5.
6.
7.
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.
------------------------------------------------------------------------------------------------------------------------------
/*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();
}
}
}
------------------------------------------------------------------------------------------------------------------------------
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.
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.
1.
2.
3.
4.
5.
6.
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();
------------------------------------------------------------------------------------------------------------------------------
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.
System.setProperty("webdriver.ie.driver", "D:\\sel\\browserdrivers\\IEDriverServer.exe");
System.setProperty("webdriver.chrome.driver", "D:\\sel\\browserdrivers\\Chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("www.google.com");
------------------------------------------------------------------------------------------------------------------------------
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);
------------------------------------------------------------------------------------------------------------------------------
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:
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();
------------------------------------------------------------------------------------------------------------------------------
1.
2.
3.
4.
5.
1.
2.
3.
4.
5.
6.
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;
* 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')].