100% found this document useful (1 vote)
33 views

Selenium WebDriver

Selenium Web driver commands

Uploaded by

hanumeshwr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
33 views

Selenium WebDriver

Selenium Web driver commands

Uploaded by

hanumeshwr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 173

Selenium Interview Questions With Answers

Part 1

1: What Is Selenium WebDriver/Selenium 2?


Answer:

 Selenium WebDriver software testing tool Is well designed object


oriented API which Is developed to automate web and mobile applications
testing process. WebDriver API Is bigger than Selenium RC but It's Architecture
Is simple and easy to understand compared Selenium RC API.
 We can automate our web application's software testing process using
selenium webdriver.
 We can say it is advanced version of selenium RC software testing tool
because some limitations of selenium RC has been overcome In selenium
WebDriver software testing tool.
 WebDriver Is designed to provide better support for dynamic changing
pages. Example : Web page elements of software web application is changing
without reloading the page. In this case WebDriver works better.
 Selenium Webdriver software testing tool Is more faster that Selenium
RC software testing tool as It Is directly Interacting with web browsers and mimic
the behavior of a real user. Example : User clicks on button of web page or
moving mouse on main menu to get the sub menu list. WebDriver works Same.
 All popular browser vendors are active participants In selenium
WebDriver's development and all of them have their own engineers team to
Improve this framework.
You can include answers of Question 2, Question 3, Question 4 and Question
5 In answer of this question If Interviewer need more detail on selenium
webdriver.

2: Tell Me WebDriver Supported Browsers?


Answer: Selenium WebDriver API has a many different drivers to test your web
application In different browsers. List of Webdriver browser drivers are as
bellow.

 Firefox Driver - For Mozilla Firefox browser


 Internet Explorer Driver - For Internet Explorer browser
 Chrome Driver - For Google Chrome browser
 HtmlUnit Driver - GUI-Less(Headless) browser for Java programs
 Opera Driver - For Opera browser
3: Tell Me WebDriver Supported Mobile Application Testing Drivers?
Answer: We can get support of mobile software application testing using
Selenium webdriver. Selenium WebDriver supports bellow given drivers to test
mobile application.
 AndroidDriver
 OperaMobileDriver
 IPhoneDriver
4: Which Programming Languages Supported By Selenium WebDriver To
Write Test Cases?
Answer: Selenium WebDriver Is very wast API and It support many different
languages to write test cases for your software web application. List of WebDriver
supported languages are as bellow.

 Java -> View Tutorials


 C#
 Python
 Ruby
 Perl
 PHP
5: Which Different Element Locators Supported By Selenium WebDriver?
Answer: Selenium WebDriver supports bellow given element locators.
 XPath Locator -> View Example
 CSSSelector Locator -> View Example
 ClassName Locator -> View Example
 ID Locator -> View Example
 Name Locator -> View Example
 LinkText Locator -> View Example
 PartialLinkText Locator -> View Example
 TagName Locator -> View Example

6: What are the benefits of automation testing.


Answer: We can get bellow given benefits If automate our software testing
process.
 Fast Test Execution : Manual software testing process Is time consuming.
Automation tests are faster and takes less time to execute tests compared to
manual test execution.
 Re-usability Of Test Cases : You need to prepare automation test cases
only one time. Then you can use same test cases for all upcoming version release
of software application. However you need to modify your test cases If there Is
any flow change of business logic changes In software. But It Is less time
consuming.
 Testing Cost Reduction : You have to put human efforts only one time to
automate your software test process. Latter on automation tool will work for you
at place of human resource.
 Better Test Coverage In Each Version Release: You have to Implement
test scenarios only once In your automation test cases. Latter on you can execute
same test cases In all upcoming release. So each scenarios will be tested In every
version release.
 Easy For Compatibility Testing : It is easy to run same tests In
combination of different OS and browser environments using automation tools.
7: Does Selenium WebDriver Support Record And Playback Facility?
Answer: No. WebDriver do not have any record and playback facility. But you
can record your tests In one of the selenium version called Selenium IDE and then
you can export your recorded tests In webdriver compatible format as per your
preferred language.

You can VIEW MORE TUTORIALS on selenium IDE or @ PART


1 and PART 2 for more details.

8: Which Operating systems support Selenium WebDriver?


Answer: At present, mainly bellow given operating systems support Selenium
WebDriver.

 Windows - Windows XP, Windows 7, Windows 8 and Windows 8.1


 Apple OS X
 Linux - Ubuntu. Other versions of linux should support too.
9: Selenium WebDriver Is Paid Or Open Source Tool? Why you prefer to
use it?
Answer: All versions of selenium software testing tool are open source. You can
use any version of selenium in free of charge.
I choose to use it because
 Open Source.
 It has multi-browser support.
 Multi-OS support.
 Multi types of locators support. So If one not works, We can use another
type.
 Web as well mobile application testing support.
 Many testers are using selenium WebDriver to automate their testing
process. So getting solution of any complex Issue very easily on Internet.
 It is extendable and flexible.
 Continues support from WebDriver's development team to improve the
API and resolve current Issues.
10: Which OpenSource Framework Is Supported In WebDriver With
Java?
Answer: Bellow given 2 java frameworks are supported by selenium
WebDriver.

 JUnit
 TestNG
You can find TestNG Tutorials links on THIS PAGE.

11: Can you tell me the syntax to open/launch Firefox browser In WebDriver
software testing tool?

Answer: We can open new Mozilla Firefox browser Instance using bellow given
syntax In WebDriver software testing tool.
WebDriver driver = new FirefoxDriver();

VIEW PRACTICAL example.

12: What Is XPath and what Is use of It In WebDriver?


Answer: In Selenium WebDriver software testing tool, XPath is used to locate
the elements. Using XPath, We can navigate through elements and attributes In
an XML document to locate software webpage elements like buttons, text box,
links, Images etc..

13: Which tool you are using to find the XPath of any element?
Answer: I am using Mozilla Firefox AddOns FireBug and FirePath to find the
XPath of software web elements. See THIS POST to download it.

VIEW MORE TUTORIALS ON SELENIUM WEBDRIVER

14: What is the difference between absolute XPath and relative XPath?
Answer:

Absolute XPath: Absolute XPath Is the full path starting from root node and ends
with desired descendant element's node. It will start using single forward slash(/)
as bellow.
Example Of Absolute XPath:

/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]
/div/div/div/div[1]/div/div/div/div[1]/div[2]/form/table/tbody/tr[1]/td/input

Above XPath Is absolute XPath of calc result box given on THIS PAGE. It
starts top node html and ends with input node.
Relative XPath: Instead of starting from root node, Relative XPath starts from
any In between node or current element's node(last node of element). It will start
using double forward slash(//) as bellow.

Example of Relative XPath:

//input[@id='Resultbox']

Above XPath Is relative XPath of same calc result box given on THIS PAGE.

15: How to Handle Dynamic Changing IDs In XPath.


Example:
//div[@id='post-body-3647323225296998740']/div[1]/form[1]/input[1]
In this XPath "3647323225296998740" Is changing every time when
reloading the page. How to handle this situation?

Answer: There are many different alternatives in such case.

Alternative 1: Look for any other attribute which is not changing every time In
that div node like name, class etc. So if this div node has class attribute then we
can write xpath as bellow.

//div[@class='post-body entry-content']/div[1]/form[1]/input[1]

Alternative 2: You can use absolute xpath(full xpath) where you not need to give
any attribute names In xpath.

/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]
/div/div/div/div[1]/div/div/div/div[1]/div[2]/div[1]/form[1]/input[1]
Alternative 3: Use starts-with function. In this xpath's ID attribute, "post-body-"
part remain same every time. So you can use xpath as bellow.

//div[starts-with(@id,'post-body-')]/div[1]/form[1]/input[1]

Alternative 4: Use contains function. Same way you can use contains function
as bellow.
div[contains(@id,'post-body-')]/div[1]/form[1]/input[1]

16: How to press ENTER key button on text box In selenium webdriver?
Answer: To press ENTER key using selenium WebDriver software automation
tool, We need to use selenium Enum Keys with Its constant ENTER as bellow.

driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Keys.ENTER);

17: How many types of waits available In selenium WebDriver


Answer: There are two types of waits available In selenium WebDriver
software automation testing tool.
1. Implicit Wait
2. Explicit Wait
VIEW TUTORIALS on Implicit and Explicit Waits with practical examples
detailed description.

18: What Is Implicit Wait In Selenium WebDriver?


Answer: Sometimes, Elements are taking time to be appear on software web
application page. Using implicit wait in webdriver software testing test case, we
can poll the DOM for certain amount of time when some element or elements
are not available immediately on webpage.
Implicit Wait Example:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

If you will write above syntax in your test, Your WebDriver test will wait 10
seconds for appearing element on page.

19: What Is Explicit Wait In Selenium WebDriver?


Answer: Using explicit wait code in selenium webdriver software automation
testing tool, you can define to wait for a certain condition to occur
before proceeding further test code execution.
Explicit Wait Example:

WebDriverWait wait = new WebDriverWait(driver, 20);


wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='gbq
fq']")));

Above code will wait for 20 seconds for targeted element to be displayed and
enabled or we can say clickable.

20: I wants to pause my test execution for fix 10 seconds at specific point.
How can I do it?
Answer: You can use java.lang.Thread.sleep(long milliseconds) method to
pause the software test execution for specific time. If you wants to pause your test
execution for 10 seconds then you can use bellow given syntax in your test.

Thread.sleep(10000);

21: How does selenium RC software testing tool drive the browser?
Answer:
When browser loaded In Selenium RC, It ‘injected’ javascript functions into the
browser and then It Is using javascript to drive the browser for software
application under test.
22: How does the selenium WebDriver drive the browser?
Answer: Selenium webdriver software testing tool works like real user
interacting with software web page and its elements. It is using each browser's
native support to make direct calls with browser for your software application
under test. There is not any Intermediate thing in selenium webdriver to Interact
with web browsers.

VIEW MORE TUTORIALS on selenium WebDriver.

23: Do you need Selenium Server to run your tests In selenium WebDriver?
Answer: It depends. If you are using only selenium webdriver API to run your
tests and you are running your all your tests on same machine then you do not
need selenium server because In this case, webdriver can directly Interact with
browser using browser's native support.

You need selenium server with webdriver when you have to perform bellow given
operations with selenium webdriver.
 When you are using remote or virtual machine to run webdriver tests for
software web application and that machine have specific browser version that is
not on your current machine.
 When you are using selenium-grid to distribute your webdriver's test
execution on different remote or virtual machines.
24: Bellow given syntax will work to navigate to specified URL In
WebDriver? Why?

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

Answer : No. It will not work and show you an exception like: "Exception in
thread "main" org.openqa.selenium.WebDriverException: f.QueryInterface is not
a function" when you run your test.
You need to provide http:// protocol with URL In driver.get method as bellow.

driver.get("http://www.google.com");

Now it will work.

25: Tell me a reason behind bellow given WebDriver exception and how will
you resolve It?
"Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Unable to locate element"
Answer: You will get this exception when WebDriver Is not able to locate
element on the page of software web application using whatever locator you have
used In your test. To resolved this Issue, I will check bellow given things.
 First of all I will check that I have placed Implicit wait code In my test or
not. If you have not placed Implicit timeout In your test and any element Is taking
some time to appear on page then you can get this exception. So I will add bellow
given line at beginning of my test case code to wait for 15 seconds for element to
be present on page. In 70% cases, this step will resolved Issue. View Practical
Example Of Implicit Wait.
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

 Another reason behind this Issue Is element's ID Is generated dynamically


every time when reloading the page. If I have used element's ID as an element
locator or used It In xpath to locate the element then I need to verify that ID of
element remains same every time or It Is changing? If It Is changing every time
then I have to use alternative element locating method. In 20% cases, This step
will resolve your Issue.
 If Implicit wait Is already added and element locator Is fine then you need
to verify that how much time It(element) Is taking to appear on page. If It Is taking
more than 15 seconds then you have to put explicit wait condition with 20 or more
seconds wait period as bellow. In 5 to 10% cases, This step will resolve your
Issue. View Example.
WebDriverWait wait = new WebDriverWait(driver, 25);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton")));
26: Can we automate desktop software application's testing using selenium
WebDriver?
Answer: No. This is the biggest disadvantage of selenium WebDriver API. We
can automate only web and mobile software application's testing using selenium
WebDriver.

27: Can you tell me the alternative driver.get() method to open URL In
browser?
Answer: We can use anyone from bellow given two methods to open URL In
web browser in selenium webdriver software testing tool.
1. driver.get()
2. driver.navigate().to()
28: Can you tell me a difference between driver.get() and driver.navigate()
methods?
Answer: Main and mostly used functions of both methods are as bellow.

driver.get()
 driver.get() method is generally used for Open URL of software web
application.
 It will wait till the whole page gets loaded.
driver.navigate()
 driver.navigate() method is generally used for navigate to URL of
software web application, navigate back, navigate forward, refresh the page.
 It will just navigate to the page but wait not wait till the whole page gets
loaded.
View more detailed description with example.
29: WebDriver has built In Object Repository. Correct me if I am wrong.
Answer: No. WebDriver do not have any built in object repository till now. But
yes, I am using java .properties file in my framework to store all required
element objects in my tests. View Example.
30: Can you tell me syntax to set browser window size to 800(Width) X
600(Height)?
Answer: We can set browser window size using setSize method of selenium
webdriver software testing tool. To set size at 800 X 600, Use bellow given
syntax in your test case.
driver.manage().window().setSize(new Dimension(500,500));

31: Can you tell me the names of different projects of selenium software
automation testing tool?
Answer: At present, Selenium software automation testing tool has four different
projects as bellow.
 Selenium IDE: It Is Firefox add-on which allows you to record and
playback your software web application's tests In Firefox browser.
 Selenium RC: It is software web application automation tool which allows
you to write your tests in many different programming languages.
 Selenium WebDriver: It is well designed object oriented API developed
to automate web and mobile software application testing process. You can write
your tests in different languages too in selenium webdriver.
 Selenium Grid: Grid allows you to execute your tests in parallel by
distributing them on different machines having different browser/OS
combinations.
32: I wants to use java language to create tests with Selenium WebDriver.
Can you tell me how to get latest version of WebDriver?
Answer: You can download language specific latest released client drivers for
selenium WebDriver software testing tool at http://docs.seleniumhq.org official
website. For java language, you will get bunch of jar files in zip folder. And then
you can add all those jar files in your project's java build path as a referenced
libraries to get support of webdriver API.

33: Can you tell me the usage of "submit" method in selenium WebDriver?
Answer: We can use submit method to submit the forms in selenium WebDriver
software automation testing tool. Example: Submitting registration form,
submitting Login form, submitting Contact Us form ect.. After filling all required
fields, we can call submit method to submit the form. VIEW EXAMPLE.

34: Do you have faced any Issue with "submit" method any time?
Answer: Yes, I have faced Issue like submit method was not working to submit
the form. In this case, Submit button of form was located outside the opening
<form> and closing </form> tags. In this case submit method will not works to
submit the form.

Also If submit button is located Inside opening <form> and closing </form> tags
but that button's type tag's attribute isn’t submit then submit method will not
work. It (type tag's attribute) should be always submit.

35: What is the syntax to type value in prompt dialog box's Input field using
selenium WebDriver?
Answer: Prompt dialog is just like confirmation alert dialog but with option of
Input text box as bellow.

To Input value in that text box of prompt dialog, you can use bellow given syntax.

driver.switchTo().alert().sendKeys("Jhon");
36: When I am running software web application's tests In Firefox Browser
using selenium webdriver, It Is not showing me any bookmarks, add-ons,
saved passwords etc. In that browser. Do you know why?
Answer: Yes. It Is because all those bookmarks, add-ons, passwords etc.. are
saved in your regular browser's profile folder so when you launch browser
manually, It will use existing profile settings so it will show you all those stuffs.
But when you run your software web application's tests in selenium webdriver, It
Is opening new browser Instance with blank/new profile. So it will not show you
bookmarks and all those things in that browser Instance.
You can create custom firefox profile and then you can use It In selenium
webdriver test. In your custom profile, you can set all required bookmarks, add-
ons etc.. VIEW THIS EXAMPLE to know how to set custom profile of firefox
browser.
37: Arrange bellow given drivers in fastest to slowest sequence?
Firefox Driver, HtmlUnit Driver, Internet Explorer Driver.
Answer: HTMLUnit Driver Is faster than all other drivers because It Is not using
any UI to execute test cases of software web application. Internet Explorer driver
is slower than Firefox and HtmlUnit driver. So, Fastest to slowest driver sequence
is as bellow.
1. HtmlUnit Driver
2. Firefox Driver
3. Internet Explorer Driver
38: What Is Ajax?
Answer: Asynchronous JavaScript and XML Is full form of AJAX which Is
used for creating dynamic web pages very fast for software web applications.
Using ajax, we can update page behind the scene by exchanging small amounts
of data with server asynchronously. That means, using ajax we can update page
data without reloading page.
39: How to handle Ajax In selenium WebDriver?
Answer: Generally we are using Implicit wait in selenium WebDriver software
automation tests to wait for some element to be present on page. But Ajax call
can not be handled using only Implicit wait In your test because page not get
reloaded when ajax call sent and received from server and we can not assume
how much time It will take to receive ajax call from server.

To handle ajax call in selenium WebDriver software automation tests, we needs


to use webdriver's FluentWait method or Explicit Waits which can wait for
specific amount of time with specific condition. You can get different Explicit
Waits examples links on THIS PAGE.

40: On Google search page, I wants to search for some words without
clicking on Google Search button. Is It possible In WebDriver? How?
Answer: Yes we can do it using WebDriver sendKeys method where we do not
need to use Google Search button. Syntax is as bellow.
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys("Search
Syntax",Keys.ENTER);

In above syntax, //input[@id='gbqfq'] is xPath of Google search text field. First


it will enter "Search Syntax" text in text box and then it will press Enter key on
same text box to search for words on Google.

41: What kind of software testing’s are possible using selenium


WebDriver? We can use it for any other purpose except testing activity?
Answer: Generally we are using selenium WebDriver for functional and
regression testing of software web applications.

42: Give me any five different xPath syntax to locate bellow given Input
element.
<input id="fk-top-search-box" class="search-bar-text fk-font-13 ac_input"
type="text" autofocus="autofocus" value="" name="q" />
Answer: Five xPath syntax for above element of software web application page
are as bellow.

//input[@id='fk-top-search-box']
//input[contains(@name,'q')]
//input[starts-with(@class, "search-bar-text")]
//input[@id='fk-top-search-box' or @name='q']
//input[starts-with(@id, 'fk-top-search-box') and contains(@class,'fk-font-
13')]

See detailed tutorial on How To Locate XPath Of Element.

43: Can you tell me two drawbacks of xPath locators as compared to


cssSelector locator?
Answer: Two main disadvantage of xPath locator as compared to cssSelector
locator are as bellow.
 It is slower than cssSelector locator.
 xPath which works In one browser may not work In other browser for same
page of software web application because some browsers (Ex. IE) reads only
Lower-cased tag name and Attribute Name. So if used It In upper case then it will
work In Firefox browser but will not work In IE browser. Every browser reads
xPath in different way. In sort, do not use xPath locators in your test cases of
software web application If you have to perform cross browser testing using
selenium WebDriver software testing tool.
44: Why xPath locator is much more popular than all other locator types In
WebDriver?
Answer: xPath locators are so much popular in selenium webdriver test case
development because
 It is very easy to learn and understand for any new user.
 There are many functions to build xPath In different ways like contains,
starts-with etc.. So if one is not possible you will have always another option to
build xPath of any element.
 Presently many tools and add-ons are available to find xpath of any
element.
45: Give me WebDriver's API name using which we can perform drag and
drop operation.
Answer: That API's name Is Advanced User Interactions API using which we
can perform drag and drop operation on page of software web application. Same
API can help us to perform some other operations too like moveToElement,
doubleClick, clickAndHold, moveToElement, etc..

View Example1 and Example2 for dragging and dropping element.

How to Drag and Drop an Element in


Selenium WebDriver
When we talk about drag and drop kind of tricky operations, we need to
use Advanced User Interactions API of selenium WebDriver. It is not so simple
and at the same time not too much hard. We need to write multiple syntax
to perform drag and drop action because you need to take multiple actions like
pick the element by clicking and holding mouse then move mouse to destination
place and then drop element by releasing mouse. Same thing you have to perform
in webdriver.
Selenium WebDriver has Advanced User Interactions API (Actions class) to
perform this kind of advanced user interactions for rich applications. We can
use Actions class and it different methods like dragAndDrop, clickAndHold,
moveToElement, release and build to composite all the actions of drag and drop
operation as shown in bellow given example. At last perform method will perform
the action.
package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DragAndDrop {

WebDriver driver = null;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/drag-and-
drop.html");
}

@Test
public void dragAndDrop() {
//Locate element which you wants to drag.
WebElement dragElementFrom =
driver.findElement(By.xpath("//div[@id='dragdiv']"));
//Locate element where you wants to drop.
WebElement dropElementTo =
driver.findElement(By.xpath("//div[@id='dropdiv']"));

//Use Actions class and Its members of WebDriver API to perform drag and
drop operation.
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(dragElementFrom)
.moveToElement(dropElementTo)
.release(dropElementTo)
.build();
dragAndDrop.perform();
}
}

Above example will drag the small square element on big square element. This is
just example. You can use this example as a reference to perform drag and drop
operation in your web application. If you wants to by specific X-Y pixel offset
then you can view THIS POST.
You can find more tutorials links HERE to start learning selenium WebDriver
from basic.
In above example, we have written total 6 lines to drag and drop an element. If
you wants convert those 6 lines in only 1 line then you can do it as bellow. Replace
bellow given 1 line with 6 lines of above example. It will do same thing.

new Actions(driver).dragAndDrop(dragElementFrom,
dropElementTo).build().perform();

So this is the way to perform drag and drop an element using selenium
WebDriver.

Selenium WebDriver: Drag and Drop


Element By Pixel(X, Y) Offset
We can use Advanced User Interactions API of selenium webdriver software
testing tool to drag the targeted element and drop it on destination element. I have
already described usage of dragAndDrop method with example In THIS POST.
Now supposing, you have an element which you wants to drag and drop by 100
pixel offset
In horizontal direction or 100 pixel offset In Vertical direction or both the
directions at the same time then you can use dragAndDropBy method of
webdriver's Actions class.
Drag And Drop Element in Horizontal Direction By 100 Pixel
If you wants to drag and drop element by 100 pixel offset In horizontal direction
then you can use syntax like bellow.
new Actions(driver).dragAndDropBy(dragElementFrom, 100, 0).build()
.perform();
Drag And Drop Element In Vertical Direction By 100 Pixel
To drag and drop element by 100 pixel offset in vertical direction, you can use
bellow given syntax in your software test case.
new Actions(driver).dragAndDropBy(dragElementFrom, 0, 100).build()
.perform();

Drag And Drop Element In Horizontal And Vertical Direction By -100


Pixel
To drag and drop element by -100 pixel offset In horizontal and vertical direction,
You can write your software test case code as bellow. Here -X offset represents
right to left direction and -Y offset represents bottom to top direction of web page.
new Actions(driver).dragAndDropBy(dragElementFrom, -100, -100).build()
.perform();

Full practical example to perform all above three operations Is as bellow.

package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DragAndDrop {

WebDriver driver = null;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/drag-and-
drop.html");
}

@Test
public void dragAndDrop() throws InterruptedException {
//Locate element which you wants to drag.
WebElement dragElementFrom =
driver.findElement(By.xpath("//div[@id='dragdiv']"));

//To drag and drop element by 100 pixel offset In horizontal direction X.
new Actions(driver).dragAndDropBy(dragElementFrom, 100, 0).build()
.perform();

//To generate alert after horizontal direction drag and drop. VIEW EXAMPLE
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Element Is drag and drop by 100 pixel
offset In horizontal direction.');");
Thread.sleep(5000);
driver.switchTo().alert().accept();

//To drag and drop element by 100 pixel offset In Vertical direction Y.
new Actions(driver).dragAndDropBy(dragElementFrom, 0, 100).build()
.perform();

//To generate alert after Vertical direction drag and drop.


javascript.executeScript("alert('Element Is drag and drop by 100 pixel
offset In Vertical direction.');");
Thread.sleep(5000);
driver.switchTo().alert().accept();

//To drag and drop element by -100 pixel offset In horizontal and -100
pixel offset In Vertical direction.
new Actions(driver).dragAndDropBy(dragElementFrom, -100, -100).build()
.perform();

//To generate alert after horizontal and vertical direction drag and drop.
javascript.executeScript("alert('Element Is drag and drop by -100 pixel
offset In horizontal and -100 pixel offset In Vertical direction.');");
Thread.sleep(5000);
driver.switchTo().alert().accept();
}
}
You can run It In your eclipse and observe the X Y direction movement
of software web element. So this is another example of selenium webdriver's
advanced user Interactions using Actions class.

Alternatively you can use moveByOffset method of selenium


WebDriver's Advanced User Interactions API to move software web element
by given pixel offset. Syntax is as bellow.

new
Actions(driver).clickAndHold(dragElementFrom).moveByOffset(100,100).release()
.perform();

46: Can we perform drag and drop operation In Selenium WebDriver? Tell
me a syntax to drag X element and drop It on Y element.
Answer: Yes, We can perform drag and drop operation using selenium
webdriver software testing tool's Advanced User Interactions API. Syntax is
like below.
new Actions(driver).dragAndDrop(X, Y).build().perform();

View Practical Example

47: Do you have faced any technical challenges with Selenium WebDriver
software test automation?
Answer: Yes, I have faced below given technical challenges during selenium
webdriver test cases development and running for software web application.
 Sometimes (Not always), Some elements like text box, buttons etc. are
taking more time(more than given Implicit wait time) to appear on page of
software web application or to get enabled on page. In such situation, If I have
used only Implicit wait then my test case can run fine on first run but It may fail
to find element on second run. So we need provide special treatment for such
elements so that webdriver script wait for element to be present or get enabled on
page of software web application during test execution. We can use Explicit wait
to handle this situation. You can find different explicit wait example links
on THIS PAGE.
 Handling dynamic changing ID to locate element is tricky. If element's ID
Is changing every time when you reload the software web application page and
you have to use that ID In XPath to locate element then you have to use functions
like starts-with(@id,'post-body-') or contains(@id,'post-body-') In XPath. Other
alternate solutions to handle this situation are described in answer of Question 15
of THIS PAGE.
 Clicking on sub menus which are getting rendered on mouse hover of main
menu is somewhat tricky. You need to use webdriver's Actions class to perform
mouse hover operation. You can VIEW FULL EXAMPLE on how to generate
mouse hover event on main menu.
 If you have to execute your test cases in multiple browsers then one test
case can run successfully In Firefox browser but same test case may fail In IE
browser due to the timing related Issues (nosuchelement exception) because test
execution In Firefox browser Is faster than IE browser. You can resolve this Issue
by Increasing Implicit wait time when you run your test In IE browser.
 Above Issue can arise due to the unsupported XPath In IE browser. In this
case, You need to you OTHER ELEMENT LOCATING METHODS (ID,
Name, CSSSelector etc.)to locate element.
 Handling JQuery elements like moving pricing slider, date picker, drag and
drop etc.. Is tricky. You should have knowledge of webdriver's Advanced User
Interactions API to perform all these actions. You can find few example links for
working with JQuery Items on THIS PAGE.
 Working with multiple Windows, Frames, and some tasks like Extracting
data from web table, Extracting data from dynamic web table, Extracting
all Links from page, Extracting all text box from page are also tricky and time
consuming during test case preparation.
 There is not any direct command to upload or download files from web
page using selenium webdriver. For downloading files using selenium webdriver,
you need to create and set Firefox browser profile with webdriver test case. You
can VIEW PRACTICAL EXAMPLE.
 Webdriver do not have any built In object repository facility. You can do
It using java .properties file to create object repository as described In THIS
EXAMPLE.
 Webdriver do not have any built in framework or facility using which we
can achieve below given tasks directly: 1. Capturing screenshots, 2. generating
test execution log, 3. reading data from files, 4. Generating test result reports,
Manage test case execution sequence. To achieve all these tasks, we have to use
external services with webdriver like Log4J to generate log, Apache POI API to
read data from excel files, Testng XSLT reports to generate test result reports.
TestNG to manage test case execution, .properties file to create object repository.
All these tasks are very time consuming. ON THIS PAGE, I have described how
to create data driven framework step by step for selenium webdriver. That
framework contains all above functionality.
You can share other webdriver technical challenges which you have faced by
commenting below so that your experience can help to others too.

48: Can you tell me a syntax to close current webdriver Instance and to
close all opened webdriver Instances?
Answer:
Yes, To close current WebDriver Instance, We can use Close() method as
bellow.
driver.close();

If there are opened multiple webdriver Instances and wants to close all of them
then we can use webdriver's quit() method as bellow in software automation
test.

driver.quit();

49: Is it possible to execute javascript directly during software test


execution? If yes then tell me how to generate alert by executing javascript
in webdriver script?

Answer:
Yes, we can execute javascript during webdriver software test execution. To
generate alert, you can write bellow given code In your script.

JavascriptExecutor javascript = (JavascriptExecutor) driver;


javascript.executeScript("alert('Javascript Executed.');");

VIEW DIFFERENT EXAMPLES to see usage of WebDriver's


JavascriptExecutor.

50: Give me a syntax to read javascript alert message string, clicking on


OK button and clicking on Cancel button.

Answer:
We can read alert message string as bellow.

String alrtmsg = driver.switchTo().alert().getText();

We can click on OK button of alert as bellow.

driver.switchTo().alert().accept();

We can click on Cancel button of alert as bellow.

driver.switchTo().alert().dismiss();

VIEW PRACTICAL EXAMPLE to handle alert, Confirmation And Prompt


popups.

51: Tell me a scenario which we can not automate in selenium WebDriver.

Answer:
1. Bitmap comparison is not possible using selenium webdriver software testing
tool.
2. Automating captcha is not possible. (Few peoples says we can
automate captcha but I am telling you If you can automate any captcha then It Is
not a captcha).
3. We can not read bar code using selenium webdriver software testing tool.

52: What Is JUnit?

Answer: Java software developers use JUnit as unit testing framework to


write repeatable tests for java programming language. It Is very simple and
open source framework and we can use It In selenium webdriver test scripts
creation to manage them In well manner.
53: Which is the latest version of JUnit.
Answer: Current latest version of JUnit Is 4.12-beta-2. This can change In future.
To check latest released version of JUnit, You can Visit JUnit Official WebSite.
54: Tell me different JUnit annotations and its usage.

Answer: JUnit has bellow given different annotations.


 @Test: @Test annotation is useful to identify method as a Test method
from software automation test script.
 @Before: @Before annotation method will be executed before each and
every @Test method.
 @After: @After annotation method will be executed after each and
every @Test method.
 @BeforeClass: @BeforeClass annotation method will be executed before
all @Test methods in a class (Means before first @Test method).
 @AfterClass: @AfterClass annotation method will be executed after all
@Test method in a class (Means after last @Test method).
 @Ignore: @Ignore annotation is useful to exclude @Test method from
execution. VIEW EXAMPLE
 @Test(timeout=1000): You can set @Test method execution timeout.
This @Test method fails Immediately when its execution time cross 1000
milliseconds.
VIEW PRACTICAL EXAMPLE of JUnit annotations with selenium
webdriver software testing tool.

55: Write sample JUnit @Test method that passes when expected
ArithmeticException thrown.

Answer: Sample JUnit @Test to pass on expected ArithmeticException Is as


bellow.
@Test(expected = ArithmeticException.class)
public void excOnDivision () {
int i = 5/0;
}

VIEW PRACTICAL EXAMPLE for Junit Timeout And Expected Exception


software Test.
56: Write sample JUnit @Test method that fails when unexpected
ArithmeticException thrown.

Answer : Sample JUnit @Test to fail on unexpected ArithmeticException Is as


bellow.
@Test
public void excOnDivision() {
int i = 5/0;
}

57: What are the advantages of TestNG over JUnit.

Answer: Advantages of TestNG over JUnit are as bellow.

 TestNG Annotations are simple and Easy to understand.


 Easy to parameterize the software test cases In TestNG.
 Easy to run software automation test cases In parallel.
 Can generate Interactive XSLT test execution reports using TestNG.

58: Tell me main features of JUnit.

Answer: JUnit features are as bellow.


 JUnit Is unit software testing framework. So It helps software developers
to create and run unit test cases very easily.
 There are many different annotations available In JUnit. Using all those
annotations, we can Identify and configure webdriver software test case very
easily.
 JUnit supports many different assertions using which we can compare
webdriver software automation test's expected and actual result.
 We can create test suite for multiple test cases to run all of them In one go
using JUnit.
 We can generate webdriver test execution HTML reports using
JUnit. VIEW EXAMPLE.
59: What are different assertions supported by JUnit?
Answer: List of JUnit assertions as bellow.
1. assertEquals
2. assertFalse
3. assertTrue
4. assertNull
5. assertNotNull
6. assertSame
7. assertNotSame
8. assertArrayEquals
60: How to create and run JUnit test suite for selenium WebDriver?

Answer: For creating JUnit software test suite, we have to create test cases class
files and one separate test suite file. Then we can write syntax like bellow in test
suite file to run test suite.

@RunWith(Suite.class)
@SuiteClasses({junittest1.class, junittest2.class })
public class junittestsuite {

In above example, junittest1.class and junittest2.class are test case class names.
VIEW PRACTICAL EXAMPLE on how to create and run JUnit test suite with
selenium WebDriver.

61: For what purpose, assertTrue and assertFalse assertions are used?
Answer: In selenium webdriver software test automation, We need to assert
Boolean conditions true and false. We can assert both these conditions using
assertTrue and assertFalse JUnit assertions.

62: Can you give me example of JUnit assertEquals assertion?

Answer: Example of JUnit assertEquals assertion Is as bellow. It assert that


values of actTotal and expTotal are equal or not.
public void sumExample() {
int val1 = 10;
int val2 = 20;
int expTotal = 35;
int actTotal = 0;
actTotal = val1 + val2;
assertEquals(actTotal, expTotal);

63: What Is TestNG?

Answer: TestNG Is Open Source (Freeware) framework which Is Inspired from


NUnit and JUnit with Introducing few new features and functionality compared
to NUnit and JUnit to make It easy to use and more powerful.

We can use TestNg with selenium webdriver software testing tool to configure
and run test cases very easily, easy to understand, read and manage test cases, and
to generate HTML or XSLT test reports.

You will find Selenium WebDriver with TestNG practical example Links
on PAGE 1 and PAGE 2.

64: Can you describe major features of TestNG?

Answer : TestNG has many major features like support of @DataProvider


annotation to perform data driven testing on software web application, can set test
case execution dependency, test case grouping, generate HTML and XSLT test
execution report for software web application etc.. VIEW MORE
FEATURES with detailed description.

65: Describe the similarities and difference between JUnit and TestNG unit
testing frameworks.

Answer: You can find all the similarities and difference between JUnit and
TestNG framework on THIS PAGE.

66: How to Install TestNG In Eclipse? How do you verify that TestNg Is
Installed properly In Eclipse?

Answer: To Install TestNG software unit testing framework In Eclipse, We have


to follow steps as described on THIS PAGE.

67: What are different annotations supported by TestNG?

Answer: TestNG supports many different annotations to configure Selenium


WebDriver software automation test. You can see mostly used annotations list
with detailed description and practical example link on THIS PAGE.

68: What is the usage of testng.xml file?

Answer: In selenium WebDriver software testing tool, we are using testng.xml


file to configure our whole test suite in single file. Few of the tasks which we
can specify In testng.xml file are as bellow.

 We can define software testing test suite using set of test cases to run
them from single place.
 Can Include or exclude test methods from software web application's test
execution.
 Can specify a group to Include or exclude.
 Can pass parameter to use in test case of software web application.
 Can specify group dependencies.
 Can configure parallel test execution for software web application.
 Can define listeners.
69: How to pass parameter with testng.xml file to use It In test case?

Answer: We can define parameter In testng.xml file using syntax like bellow.

<parameter name="browser" value="FFX" />

Here, name attribute defines parameter name and value defines value of that
parameter. Then we can use that parameter in selenium webdriver software
automation test case using bellow given syntax.

@Parameters ({"browser"})

VIEW FULL EXAMPLE on how to define and use parameter from testng.xml
file.

70: I have a test case with two @Test methods. I wants to exclude one
@Test method from execution. Can I do it? How?

Answer: Yes you need to specify @Test method exclusion In testng.xml file as
bellow.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >


<suite name="Test Exclusion Suite">
<test name="Exclusion Test" >
<classes>
<class name="Your Test Class Name">
<methods>
<exclude name="Your Test Method Name To Exclude"/>
</methods>
</class>
</classes>
</test>
</suite>

You need to provide @Test method name in exclude tag to exclude it from
execution.

You can VIEW DETAILED EXAMPLE on how to exclude specific @Test


method from execution.

71: Tell me syntax to skip @Test method from execution.

Answer: You can use bellow given syntax Inside @Test method to skip It from
test execution.

throw new SkipException("Test Check_Checkbox Is Skipped");

It will throw skip exception and @Test method will be sipped immediately from
execution. You can VIEW FULL EXAMPLE on how to skip @Test method
from execution.

72: Arrange bellow give testng.xml tags from parent to child.

<test>
<suite>
<class>
</methods>
</classes>

Answer: Parent to child arrangement for above testng tags Is as bellow.

<suite>
<test>
</classes>
<class>
</methods>

73: How to set priority of @Test method? What Is Its usage?


Answer: In your software web application's test case, you can set priority for
TestNG @Test annotated methods as bellow.
@Test(priority=0)

Using priority, We can control @Test method execution manner as per our
requirement. That means @Test method with priority = 0 will be executed 1st and
@Test method with priority = 1 will be executed 2nd and so on. VIEW
PRACTICAL EXAMPLE to know how to use It.

74: Tell me any 5 assertions of TestNG which we can use In selenium


webdriver software testing tool.

Answer: There are many different assertions available In TestNG but generally I
am using bellow given assertions In my test cases.
1. assertEquals VIEW EXAMPLE
2. assertNotEquals VIEW EXAMPLE
3. assertTrue VIEW EXAMPLE
4. assertFalse VIEW EXAMPLE
5. assertNull VIEW EXAMPLE
6. assertNotNull VIEW EXAMPLE

75: Can you tell me usage of TestNG Soft Assertion In selenium webdriver
software testing tool?

Answer: Using TestNG soft assertion, we can continue our test execution even if
assertion fails. That means on failure of soft assertion, remaining part of @Test
method will be executed and assertion failure will be reported at the end of @Test
method. VIEW PRACTICAL EXAMPLE.
76: How to write regular expression In testng.xml file to search @Test
methods containing "product" keyword.

Answer: Regular expression to find @Test methods containing keyword


"product" Is as bellow in selenium webdriver software testing tool.
<methods>
<include name=".*product.*"/>
</methods>

VIEW EXAMPLE OF USING REGULAR EXPRESSION

77: Which time unit we provide In time test? minutes? seconds?


milliseconds? or hours? Give Example.

Answer: Time unit we provide on @Test method level or test suite level Is In
milliseconds. You can VIEW FULL EXAMPLE to know how to set time out.

78: What Is the syntax to get value from text box and store It In variable.

Answer: Most of the time, String In text box will be stored as value. So we need
to access value attribute(getAttribute) of that text box as shown In bellow
example.

String Result =
driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value"
);

VIEW PRACTICAL EXAMPLE to get text from calc result text box.

79: What Is the difference between findelement and findElements ?


Answer: findElement Is useful to locate and return single element from page of
software web application while findElements Is useful to locate and return
multiple elements from software web page.

VIEW DETAILED DESCRIPTION WITH EXAMPLE.

80: Tell me looks like XPath of sibling Input element which Is after Div in
the DOM.

Answer: XPath for above scenario will be something like bellow.


//div/following-sibling::input

81: Tell me looks like CSSSelector path of sibling Input element which Is
after Div in the DOM.

Answer: CSSSelecor path will looks like bellow.


css=div + input

82: What Is Parallelism In TestNG?

Answer: In general software term, Parallelism means executing two part of


software program simultaneously or executing software program simultaneously
or we can say multithreaded or parallel mode. TestNG has same feature using
which we can start multiple threads simultaneously In parallel mode and test
methods will be executed In them. VIEW PARALLELISM EXAMPLE.

83: What are the benefits of parallelism over normal execution?

Answer: Using parallelism facility of TestNG In selenium webdriver,


 Your software test execution time will be reduced as multiple tests will be
executed simultaneously.
 Using parallelism, We can verify multithreaded code In software
application.
84: I wants to run test cases/classes In parallel. Using which attribute and
value I can do It?

Answer: You have to use parallel = classes attribute In testng.xml to run


software web app tests parallel. VIEW EXAMPLE.

85: What Is dependency test In TestNG?

Answer: Dependency Is very good feature of testng using which we can set
software test method as dependent test method of any other single or multiple or
group of test methods. That means depends-on method will be executed first and
then dependent test method will be executed. If depends-on software test method
will fail then execution of dependent test method will be skipped automatically.
TestNG dependency feature will works only If depends-on test method Is part of
same class or part of Inherited base class. DETAILED DESCRIPTION ON
DEPENDENCY.

86: What Is the syntax to set test method dependency on multiple test
methods.

Answer: We can set test method's dependency on multiple test methods as


bellow.

@Test(dependsOnMethods={"Login","checkMail"})
public void LogOut() {
System.out.println("LogOut Test code.");
}
Above test method Is depends on Login and checkMail test methods. VIEW
EXAMPLE.

87: What Is the syntax to set test method disabled.

Answer: We can use attribute enabled = false with @Test annotation to set test
method disabled. Syntax Is as bellow.

@Test(enabled = false)
public void LogOut() {
System.out.println("LogOut Test code.");
}

Disabled software test methods will be excluded automatically during


execution. VIEW PRACTICAL EXAMPLE.

88 : In XPath, I wants to do partial match on attribute value from beginning.


Tell me two functions using which I can do It.

Answer : We can use bellow given two functions with XPath to find element for
software web page using attribute value from beginning.
1. contains()
2. starts-with()
89 : I have used findElements In my software test case. It Is
returning NoSuchElementException when not element found. Correct me If
I am wrong.

Answer : It Is Incorrect. findElements will never


return NoSuchElementException. It will return just an empty list.
90 : My Firefox browser Is not Installed at usual place. How can I tell
FirefoxDriver to use It?

Answer : If Firefox browsers Is Installed at some different place than the usual
place then you needs to provide the actual path of Firefox.exe file as bellow.

System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla
Firefox\\Firefox.exe");
driver =new FirefoxDriver();

91 : How to create custom firefox profile and how to use It In selenium


webdriver software test?

Answer : You can view detailed answer for firefox custom profile on THIS
PAGE.

92 : What versions of Internet Explorer are supported by selenium


WebDriver software testing tool?

Answer : Till date, Selenium WebDriver software testing tool supports IE 6, 7,


8, 9, 10 and 11 with appropriate combinations of Windows 7, Vista or XP.

93 : Tell me the class name using which we can generate Action chain.

Answer : The WebDriver class name Using which we can generate Action chain
Is "Actions". VIEW USAGE OF ACTIONS CLASS with practical example on
how to generate series of actions to drag and drop element of software web
application.
94 : Do you know method name using which we can builds up the actions
chain?

Answer : Method name of Actions class to build up actions chain Is


"build()". THIS EXAMPLE will show you how to build drag and drop element
on software web page by x,y pixel actions using build() method.

95 : When we can use Actions class In Selenium WebDriver test case?

Answer : Few of the examples are bellow where can use actions class to perform
operations In software web application.
 Drag and drop element - VIEW EXAMPLE
 Drag and drop by x,y pixel offset - VIEW EXAMPLE
 Selecting JQuery selectable Items - VIEW EXAMPLE
 Moving JQuery slider - VIEW EXAMPLE
 Re-sizing JQuery re-sizable element - VIEW EXAMPLE
 Selecting date from JQuery date picker - VIEW EXAMPLE
96 : Can we capture screenshot In Selenium WebDriver software testing
tool? How?

Answer : We can use selenium webdriver TakesScreenshot method to capture


screenshot. Java File class will be used to store screenshot In your system's local
drive. You can view how to capture screenshot In selenium webdriver on THIS
PAGE.

97 : Selenium WebDriver has any built In method using which we can read
data from excel file?

Answer : No, Selenium webdriver software testing tool do not have any built In
functionality using which we can read data from excel file.
98 : Do you know any external API name using which we can read data from
excel file?

Answer :
 We can use jxl API (Java Excel API) to read data from excel file. VIEW
EXAMPLE
 We can use one more powerful API known as Apache POI API to read and
write data In excel file. I have created data driven framework using Apache POI
API. You can VIEW DATADRIVEN FRAMEWORK CREATION
TUTORIALS step by step.
99 : Tell me any 5 webdriver common exceptions which you faced during
software test case execution.

Answer : WebDriver's different 5 exceptions are as bellow.


1. TimeoutException - This exception will be thrown when command
execution does not complete In given time.
2. NoSuchElementException - WebDriver software testing tool will
throw this exception when element could not be found on page of software
web application.
3. NoAlertPresentException - This exception will be generated when
webdriver ties to switch to alert popup but there Is not any alert present on
page.
4. ElementNotSelectableException - It will be thrown when
webdriver Is trying to select unselectable element.
5. ElementNotVisibleException - Thrown when webdriver Is not able
to Interact with element which Is available In DOM but It Is hidden.
6. StaleElementReferenceException - VIEW DESCRIPTION.

100 : Tell me different ways to type text In text box In selenium software test.
Answer : We can type text In text box of software web application page using
bellow given ways In selenium test.

1.Using .SendKeys() method

driver.findElement(By.xpath("//input[@id='fname']")).sendKeys("Using
sendKeys");

2. Using JavascriptExecutor

((JavascriptExecutor)driver).executeScript("document.getElementById('fname').
value='Using JavascriptExecutor'");

3. Using Java Robot class VIEW EXAMPLE

driver.findElement(By.xpath("//input[@id='fname']")).click();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_U);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_N);
robot.keyPress(KeyEvent.VK_G);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_B);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_T);

101 : Tell me different ways to verify element present or not on page.

Answer : We can check If element Is present or not on page of software we


application using bellow given 2 simple ways.
1. Using .size() method

Boolean elePresent = driver.findElements( By.id("ID of element") ).size() !=


0;

If above syntax return "false" means element Is not present on page and "true"
means element Is present on page.

2. Using .isEmpty() method

Boolean elePresent = driver.findElements(By.id("ID of element")).isEmpty();

If this returns "true" means element Is not present on page and "false" means
element Is present on page.

102 : Why we need to customize Firefox browser profile In webdriver test?

Answer : Webdriver launch fresh browser Instance when we run software tests
In Firefox browser using selenium webdriver. Fresh browser Instance do not have
any Installed add-ons, saved passwords, bookmarks and any other user
preferences. So we need to create custom profile of Firefox browser to get any of
this thing In Webdriver launched browser. VIEW MORE DETAIL WITH
EXAMPLE

103 : How to customize Firefox browser profile for webdriver software


test?

Answer : You can do It In two different ways.


1. You can create your desired firefox browser profile before running
software automation test and then you can use It In your selenium
webdriver software test. VIEW EXAMPLE.
2. You can customize your firefox browser profile run time before
launching webdriver's Firefox browser Instance. VIEW EXAMPLE.
104 : What is Difference between getAttribute() and getText()?

Answer :
 getAttribute() method Is useful to read software web app element's attribute
value like id, name, type etc. VIEW EXAMPLE.
 getText() method Is useful to read text from element or alert. VIEW
EXAMPLE.
105 : What is the difference between WebDriver and Remote WebDriver?

Answer : Simple answer for this questions Is as bellow.


 WebDriver : Webdriver Is an Interface or we can say software testing tool
using which we can create automated test cases for web application and then run
on different browsers like IE, Google chrome, Firefox etc.. We can create test
cases In different languages. VIEW MORE DETAIL.
 Remote WebDriver : Remote WebDriver Is useful to run test cases In
same machine or remote machines using selenium Grid.
106 : I have total 200 test cases. I wants to execute only 20 test cases out of
them. Can I do It In selenium WebDriver? How?

Answer : Yes. If you are using TestNG with selenium webdriver software testing
tool then you can do Is using grouping approach as described In THIS PAGE.
Create separate group for those 20 test cases and configure testng.xml file
accordingly to run only those 20 test cases.

Also If you are using data driven framework then you can configure It In excel
file. You can configure such data driven framework at your own by following
steps given on THIS PAGE.

107 : Can you tell me three different ways to refresh page. Do not
use .refresh() method.
Answer : We can refresh browser In many different ways. Three of them are as
bellow.

driver.get(driver.getCurrentUrl());

driver.navigate().to(driver.getCurrentUrl());

driver.findElement(By.xpath("//h1[@class='title']")).sendKeys(Keys.F5);

108 : I wants to pass parameter In software test case through testng.xml file.
How can I do It?

Answer : You can use <parameter> node under <test> node In testng.xml file
with parameter name and value. Then you can use @Parameters annotation with
parameter name In your test case of software web application. VIEW USAGE
OF @PARAMETER ANNOTATION.

109 : My page contains file upload field but I am not able to upload file using
selenium webdriver software testing tool. Is there any other way using which
I can upload file In selenium test?

Answer : If you are not able to upload file using selenium webdriver then you
can create file upload script In AutoIT and then you can use It In selenium
webdriver software test. You can refer bellow given articles to learn more about
It.
 What Is AutoIT V3
 Steps To Download And Install AutoIT V3
 Creating AutoIt Script To Upload File On Web Page
 Upload File In Selenium WebDriver Using AutoIt
110 : I wants to set size and position of my browser window. Do you know
how to do it in selenium webdriver?

Answer : We can use setSize function to set size of window and setPosition
function to set position of browser window. VIEW EXAMPLE.

111 : Is there any way to get size and position of browser window in selenium
webdriver?

Answer : Yes.. We can get it using webdriver functions getSize


and getPosition. VIEW MORE

112 : I wants to scroll my software web application page by 300 pixel. Tell
me how can i do it?

Answer : We can use javascript executor with window.scrollBy(x,y) to scroll


page in x or y directions. VIEW MORE DETAIL

1. WebDriver Basic Action Commands And Operations With


Examples
2. Opening And Maximizing Firefox Browser And Opening URL
3. Clicking On Button
4. Submitting Form Using .submit() Method
5. Store Text Of Element
6. Typing Text In To Text box
7. Get Page Title Of Software Web Application
8. Get Current Page URL
9. Get Domain Name
10. Generating Alert Manually
11. Selecting Value From Dropdown Or Listbox
12. Deselecting Value From Dropdown Or Listbox
13. Navigating Back And Forward
14. Verify Element Present
15. Capturing Entire Page Screenshot
16. Generating Mouse Hover Event
17. Handling Multiple Windows
18. Verify Element Is Enabled Or Not
19. Enable/Disable Element
20. Handling Alert, Confirmation and Prompt popup
21. Handle Unexpected Alert Of Software Web Application
22. Highlighting element Of Software Web Application
23. Reading Font Properties Using .getCssValue()

WebDriver Wait For Examples Using JUnit And Eclipse

1. How to apply implicit wait in selenium WebDriver script


2. Explicit Wait - For Element
3. Explicit Wait - For Text
4. Explicit Wait - For Alert
5. Explicit Wait - For Element Visible
6. Explicit Wait - For Element Invisible

WebDriver Other Examples

1. findElement() And findElements() Difference


2. Generating Log In WebDriver
3. Creating Object Repository Using Properties File
4. Extracting All Links From Page
5. Extracting All Text Box From Page
6. Extracting/Reading Table Data
7. Handle Dynamic Web Table
8. Create And Use Custom Firefox Profile In Selenium
WebDriver Test
9. Downloading Files Using Selenium WebDriver
10. Handling Ajax Auto Suggest Drop List
11. Parameterization/Data Driven Testing
12. Selenium WebDriver Interview Questions

TestNG Framework Tutorials

1. Introduction Of TestNG
2. TestNG Installation Steps
3. Similarities and Difference Between TestNG and JUnit
4. Create And Run First TestNG-WebDriver Test
5. TestNg annotations with examples
6. Creating And Running WebDriver Test Suit Using testng.xml
File
7. Creating Single Or Multiple Tests For Multiple Classes
8. Creating Test Suite Using Class From Different Packages
9. Creating Test Suite Using Selected Or All Packages
10. Including Only Selected Test Methods In Selenium WebDriver-
TestNg Test
11. testng.xml - Include/Exclude Selenium WebDriver Test
Package
12. testng.xml - Using Regular Expression To Include/Exclude Test
Method
13. testng.xml - Skip Test Intentionally Using SkipException()
14. Data driven Testing using @DataProvider Annotation Of
TestNG
15. Parallel test execution In multiple browsers using @Parameters
annotation

WebDriver Assertions With TestNG


Hard Assertions :

1. assertEquals Assertion With Example


2. assertNotEquals Assertion With Example
3. assertTrue Assertion With Example
4. assertFalse Assertion With Example
5. assertNull Assertion With Example
6. assertNotNull Assertion With Example
Soft Assertion :
Applying TestNG Soft Assertion With Example

Common Functions To Use In WebDriver Test

1. Common Function To Compare Two Strings


2. Common Function To Compare Two Integers
3. Common Function To Compare Two Doubles
4. Common Function To Open And Close Browser
5. Common Function To LogIn And LogOut
Selenium WebDriver Tutorials - Basic Action
Commands And Operations With Examples
1. Creating New Instance Of Firefox Driver

WebDriver driver = new FirefoxDriver();

Above given syntax will create new instance of Firefox driver. VIEW
PRACTICAL EXAMPLE

2. Command To Open URL In Browser

driver.get("http://only-testing-blog.blogspot.com/2013/11/new-test.html");

This syntax will open specified URL of software web application in web
browser. VIEW PRACTICAL EXAMPLE OF OPEN URL

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. VIEW


PRACTICAL EXAMPLE OF CLICK ON ELEMENT

4. Store text of targeted element in variable

String dropdown = driver.findElement(By.tagName("select")).getText();

This syntax will retrieve text from targeted element of software web application
page and will store it in variable = dropdown. VIEW PRACTICAL
EXAMPLE OF Get Text

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. VIEW
PRACTICAL EXAMPLE OF SendKeys

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 of software web application. VIEW PRACTICAL EXAMPLE OF
IMPLICIT WAIT

7. Applying Explicit wait in webdriver with WebDriver canned conditions.

WebDriverWait wait = new WebDriverWait(driver, 15);


wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div
[@id='timeLeft']"), "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. VIWE DIFFERENT
PRACTICAL EXAMPLES OF EXPLICIT WAIT

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. VIEW PRACTICAL EXAMPLE OF GET TITLE

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. VIEW PRACTICAL EXAMPLE OF GET CURRENT 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. VIEW GET DOMAIN NAME PRACTICAL EXAMPLE.

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. VIEW
PRACTICAL EXAMPLE OF GENERATE ALERT USING SELENIUM
WEBDRIVER.

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).


VIEW PRACTICAL EXAMPLES OF SELECTING VALUE FROM
DROP DOWN LIST.

 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 of software application's page.

VIEW PRACTICAL EXAMPLES OF DESELECT SPECIFIC OPTION


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.VIEW
PRACTICAL EXAMPLE OF isMultiple()
13. Navigate to URL or Back or Forward in Selenium Webdriver

driver.navigate().to("http://only-testing-
blog.blogspot.com/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 navigate one step forward.VIEW PRACTICAL
EXAMPLES OF NAVIGATION COMMANDS.

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. VIEW PRACTICAL EXAMPLE OF VERIFY
ELEMENT PRESENT.

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. VIEW


PRACTICAL EXAMPLE ON THIS PAGE.

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. VIEW PRACTICAL
EXAMPLE OF MOUSE HOVER.

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. VIEW PRACTICAL EXAMPLE OF
HANDLING MULTIPLE WINDOWS IN WEBDRIVER

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. VIEW PRACTICAL EXAMPLE OF
VERIFY ELEMENT IS ENABLED OR NOT.

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. VIEW PRACTICAL EXAMPLE
OF ENABLE/DISABLE TEXTBOX.

20. Selenium WebDriver Assertions With TestNG Framework

 assertEquals
Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal
values. VIEW PRACTICAL EXAMPLE OF assertEquals ASSERTION

 assertNotEquals
Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values. VIEW
PRACTICAL EXAMPLE OF assertNotEquals ASSERTION.

 assertTrue
Assert.assertTrue(condition);
assertTrue assertion works for boolean value true assertion. VIEW
PRACTICAL EXAMPLE OF assertTrue ASSERTION.

 assertFalse
Assert.assertFalse(condition);
assertFalse assertion works for boolean value false assertion. VIEW
PRACTICAL EXAMPLE OF assertFalse ASSERTION.

21. Submit() method to submit form

driver.findElement(By.xpath("//input[@name='Company']")).submit();
It will submit the form. VIEW PRACTICAL EXAMPLE OF SUBMIT
FORM.

22. Handling Alert, Confirmation and Prompts Popups


String myalert = driver.switchTo().alert().getText();
To store alert text. VIEW PRACTICAL EXAMPLE OF STORE ALERT
TEXT

driver.switchTo().alert().accept();
To accept alert. VIEW PRACTICAL EXAMPLE OF ALERT ACCEPT

driver.switchTo().alert().dismiss();
To dismiss confirmation. VIEW PRACTICAL EXAMPLE OF CANCEL
CONFIRMATION

driver.switchTo().alert().sendKeys("This Is John");
To type text In text box of prompt popup. VIEW PRACTICAL EXAMPLE
OF TYPE TEXT IN PROMPT TEXT BOX

Locating Web Element By ClassName In


Selenium WebDriver with example
There are many different ways of locating elements in webdriver for your
software web application page and I have described one of them in
my PREVIOUS POST with example. In webdriver, we can't do any thing on
web page of software web application if you don't know how to locate an element.
As you know, we can use element's ID to locate that specific element but suppose
if your element do not have any ID then how will you locate that element on page
of software application? Locating web element by className is good
alternative if your element contains class name. We can locate element By Tag
Name, By Name, By Link Text, By Partial Link Text, By CSS and By XPATH
too but will look about them in my next posts.

Create selenium webdriver data driven framework from scratch @This Page.
How to get the class name of element
You can get the class name of element using firebug add-on software as shown
in bellow given image.

Look in to above image. Post date content has a class and we can use that class
name to store that blog post date string. Notice one more thing in above image,
blog post date string has not any ID so we can not locate it by ID.

(Note : You can view more webdriver tutorials on THIS LINK.)

Example Of Locating Web Element By ClassName


We can use bellow given syntax to locate that element of software web
application.

driver.findElement(By.className("date-header"));

Practical example of locating web element by className is as bellow.


package junitreportpackage;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Mytest1 {


//To open Firefox browser
WebDriver driver = new FirefoxDriver();

@Before
public void beforetest() {

//To Maximize Browser Window


driver.manage().window().maximize();

//To Open URL In browser


driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
}

@After
public void aftertest() {
driver.quit();

@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
String datentime = driver.findElement(By.className("date-
header")).getText();//Locating element by className and store its text to
variable datentime.
System.out.print(datentime);
}

In above example,

Open Browser
WebDriver driver = new FirefoxDriver() will open webdriver's Firefox
browser instance.

Open URL
driver.get(); will open targeted URL in browser.

Maximize Browser Window


driver.manage().window().maximize(); will maximize browser window.

View THIS POST to know how to run webdriver test in google chrome and
View THIS POST to know how to run webdriver test in IE browser..

How To Locate Elements By ID In Selenium


WebDriver With Example
Before using WebDriver software testing tool, You must be aware about different
ways of locating an elements in WebDriver for software web application.
Locating an element is essential part in selenium WebDriver because when you
wants to take some action on element (typing text or clicking on button of
software web application), first you need to locate that specific element to
perform action. Let's learn how to locate element by ID.

First of all I recommend you to read all these selenium IDE element locating
methodsand then read this article about Selenium WebDriver element locators to
get all locating methods in better way.

WebDriver software testing tool which is also known as a Selenium 2 has many
different ways of locating element. Let me explain each of them with examples.
Here I am explaining how to locate element By id and will describe Locating
Web Element By ClassName in my Next Post and others in latter posts.

Locating UI Element By ID
If your software web application's page element has unique and static ID then you
can locate your page element by ID. Look in to bellow given image. You can
verify that your webelement has any id or not using the firebug.

In above image, Submit Query button has unique id = 'submitButton'. I can use
that id to locate button as bellow.

driver.findElement(By.id("submitButton"));

Bellow given example will show you how to locate element by id and then how
to click on it. Copy bellow given @Test method part and replace it with the
@Test method part of example given on this page.(Note : @Test method is
marked with pink color in that example).

@Test
public void test() {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
for (int i = 0; i<=20; i++)
{
WebElement btn = driver.findElement(By.id("submitButton"));//Locating
element by id
if (btn.isEnabled())
{
//if webelement's attribute found enabled then this code will be
executed.
System.out.print("\nCongr8s... Button is enabled and webdriver is
clicking on it now");

//Locating button by id and then clicking on it.


driver.findElement(By.id("submitButton")).click();
i=20;

}
else
{
//if webelement's attribute found disabled then this code will be
executed.
System.out.print("\nSorry but Button is disabled right now..");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Submitting Form Using submit() Method Of


Selenium WebDriver
You will find many forms In any software web application like Contact Us form,
New User Registration Form, Inquiry Form, LogIn Form etc.. Supposing you are
testing one software website where you have to prepare Login form submission
test case In selenium webdriver then how will you do It? Simplest way Is
described In THIS POST. If you will see In that example post, we have used
.click() method to click on Login button.

Selenium Webdriver software testing tool has one special method to submit any
formand that method name Is submit(). submit() method works same as clicking
on submit button.
WEBDRIVER TUTORIAL PART 2

When to use .click() method


You can use .click() method to click on any button of software web application.
Means element's type = "button" or type = "submit", .click() method will works
for both.

When to use .submit() method


If you will look at firebug view for any form's submit button then always It's type
will be "submit" as shown In bellow given Image. In this case, .submit() method
Is very good alternative of .click() method.

Final Notes :
1. If any form has submit button which has type = "button" then .submit() method
will not work.
2. If button Is not Inside <form> tag then .submit() method will not work.

Now let us take a look at very simple example where I have used .submit() method
to submit form on software web page. In bellow given example, I have not used
.click() method but used .submit() method with company name field. Run bellow
given example In eclipse with testng and verify the result.
package Testng_Pack;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Form_Submit {

WebDriver driver = new FirefoxDriver();

@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-
blog.blogspot.in/2014/05/form.html");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

@Test
public void LogIn_Test(){

driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("MyFName"
);

driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("MyLName")
;
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("My
Email ID");
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("My Mob
No.");
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("My Comp
Name");
//To submit form.
//You can use any other Input field's(First Name, Last Name etc.) xpath
too In bellow given syntax.
driver.findElement(By.xpath("//input[@name='Company']")).submit();
String alrt = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alrt);
}
}

Above example will simply submit the form and retrieve submission alert to print.
So this way we can use webdriver's submit method to submit any form. You can
try different form for your better understanding.

Element Locators In Selenium 2 or


WebDriver - Locating Element By Tag Name
We have learn about Locating element by ID and Locating element by Class
Name for application software web page with examples in my previous posts. Let
me repeat once more that if software web page's element contains ID then we
can locate element by its ID and if software web page's element do not have ID
and contains Class Name then we can locate an element by Class Name.

Now supposing, software web element do not have any ID or Class Name then
how to locate that element in selenium WebDriver ? Answer is there are many
alternatives of selenium WebDriver element locators and one of them
is Locating Element By Tag Name.

Locating Element By Tag Name is not too much popular because in most of cases,
we will have other alternatives of element locators. But yes if there is not any
alternative then you can use element's DOM Tag Name to locate that element in
webdriver.
(Note : You can view all tutorials of webdriver element locators)
Look in to above image. That select box drop down do not have any ID or Class
Name. Now if we wants to locate that element then we can use it's DOM tag name
'select' to locate that element. Element locator sysntex will be as bellow.

driver.findElement(By.tagName("select"));

Bellow given example will locate dropdown element by it's tagName to store its
values in variable. Copy bellow given @Test method part and replace it with the
@Test method part of example given on this page.(Note : @Test method is
marked with pink color in that example).

@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by tagName and store its text in to variable dropdown.
String dropdown = driver.findElement(By.tagName("select")).getText();
System.out.print("Drop down list values are as bellow :\n"+dropdown);
}
Selenium Webdriver Element Locator -
Locating Element By Name With Example
Selenium WebDriver/Selenium 2 is web and mobile software application
regression testing tool and it is using element locators to find out and perform
actions on web elements of software application. We have learn Element
Locating by ID, Element Locating By Tag Name and Locating element by
Class Name with examples in my previous posts. Locating Element By Name is
very useful method and many
peoples are using this method in their webdriver software automation test case
preparation. Locating Element By Name and Locating Element by ID are nearly
same. In Locating Element by ID method, webdriver will look for the specified
ID attribute and inLocating Element By Name method, webdriver will look for
the specified Name attribute on page of software web application.

Let me show you one example of how to locate element by name on page of
software web application and then we will use it in our webdriver test case for
software web application.

Look in to above image, web element 'First Name' input box do not have any ID
so webdriver can not locate it By ID but that element contains name attribute. So
webdriver can locate it By Name attribute. Syntax of locating element in
webdriver is as bellow.
driver.findElement(By.name("fname"));

Now let we use it in one practical example as bellow.Copy bellow given @Test
method part and replace it with the @Test method part of example given on this
page.
(Note : @Test method is marked with pink color in that example).

@Test
public void test()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
//Locating element by Name and type given texts in to input box.
driver.findElement(By.name("fname")).sendKeys("My First Name");
}

Above example will type the text in text box using By Name element locating
method.

Selenium WebDriver wait for title with


example
WebDriver has many Canned Expected Conditions by which we can
force webdriver to wait explicitly. However Implicit wait is more practical than
explicit wait in WebDriver software testing tool. But in some special cases
where implicit wait is not able to handle your scenario then in that case you need
to use explicit waits in your software automation test cases. You can view
different posts on explicit waits where I have described WebDriver's different
Canned Expected conditions with examples.

Create selenium webdriver software automation data driven framework from


scratch@This Page.

If you have a scenario where you need to wait for title then you can
use titleContains(java.lang.String title) with webdriver wait. You need to provide
some part of your expected software web application page title with this condition
as bellow.

WebDriverWait wait = new WebDriverWait(driver, 15);


wait.until(ExpectedConditions.titleContains(": MyTest"));

In above syntax, ": MyTest" is my web page's expected title and 15 seconds is
max waiting time to appear title on web page. If title will not appears within 15
seconds due to the any reason then your test case will fails with timeout error.

First run bellow given test case in your eclipse and then try same test case for
your own software application.

Copy bellow given @Test method part of wait for title example and replace it
with the @Test method part of example given on this page. (Note : @Test
method is marked with pink color in that linked page).

@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
driver.findElement(By.xpath("//a[contains(text(),'Click Here')]")).click();

//Wait for page title


WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains(": MyTest"));

//Get and store page title in to variable


String title = driver.getTitle();
System.out.print(title);
}
In above example, when webdriver will click on Click Here link, another page
will open. During page navigation, webdriver will wait for expected page title of
software web application.

Executing javascript in selenium webdriver


to get page title with example
JavascriptExecutor is very useful Interface in webdriver software testing tool.
Interface JavascriptExecutor helps you to execute javascript in your software
test case whenever required. If you knows/remember, We had seen Different
examples of executing javascript in selenium IDE to perform different actions.
Let me give you one example of executing javascript in selenium
WebDriver software testing tool.

Sometimes in your test case, you needs to store your software web
application page title to compare it with expected page title. In selenium IDE, we
can use "storeTitle" command to store it in variable. In webdriver ,we can do it
directly usingdriver.getTitle(); as shown in this example. But if you wants to do
it using javascript then how will you do it?

Example : Get page title using javascript in selenium webdriver

Copy bellow given @Test method part of get page title using javascript example
and replace it with the @Test method part of example given on this page. (Note
: @Test method is marked with pink color in that linked page).

@Test
public void test ()
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;

//Get current page title


String pagetitle=(String)javascript.executeScript("return document.title");
System.out.println("My Page Title Is : "+pagetitle);
//Get current page URL
String CurrentURL = driver.getCurrentUrl();
System.out.println("My Current URL Is : "+CurrentURL);
}

(View more JavascriptExecutor examples in webdriver)

In above example, I have used JavascriptExecutor to execute java script in


selenium webdriver software testing tool. Inner javascript will return current
page title and store it in variable = pagetitle. Then Next statement will print it in
the console. You can use that variable value to compare with your expected
page title if required.

Last 2 syntax will get current page URLs and Print it in console.

Selenium WebDriver - Get Domain Name


Using JavascriptExecutor
You need current software web application's page URL when you have to
compare it with your expected URL. You can do it using WebDriver basic
operation command driver.getCurrentUrl();. This method we have seen in
my Previous Post. If you remember, we can use "storeLocation" command to
get current software web application's page URL in selenium IDE software
testing tool. Main purpose of this post is to explore how to get domain name in
webdriver. So if you wants to store application's domain name then you need
to use JavascriptExecutor in your software test case.

Look here, software application's domain name is different than the current page
URL.

If my current page URL = http://only-testing-blog.blogspot.in/2013/11/new-


test.htmlThen
My domain name is = only-testing-blog.blogspot.in
Let me provide you simple example of how to get current software web
application's page URL using driver.getCurrentUrl(); and how to get domain
name using JavascriptExecutor.

Example : Get current URL of page and domain name in selenium webdriver
Copy bellow given @Test method part of get current software web
application's page URL using javascript example and replace it with the @Test
method part of example given on THIS PAGE. (Note : @Test method is
marked with pink color in that linked page).

@Test
public void test ()
{
String CurrentURL = driver.getCurrentUrl();
System.out.println("My Current URL Is : "+CurrentURL);

//Get and store domain name in variable


JavascriptExecutor javascript = (JavascriptExecutor) driver;
String DomainUsingJS=(String)javascript.executeScript("return
document.domain");
System.out.println("My Current URL Is : "+DomainUsingJS);
}

(View more Javascript examples in selenium webdriver)

In above example, 1st 2 syntax will get and print current page URL. Last 3 syntax
will get domain name using javascript and will print it in console.

Generating Alert In Selenium Webdriver


using JavascriptExecutor
If you need to generate alert during your software test case execution then you
can use java script Executor in selenium webdriver software testing tool. Java
Script Executor is very helpful interface of selenium webdriver because using it
we can execute any java script. I think manual alert generation in webdriver
test is required only in rare case but main purpose of this post is to explore Java
Script Executor. You can view more examples of JavascriptExecutor on THIS
LINK.

If you remember, we can generate alert in selenium IDE software testing tool too
using "runScript" command. THIS POST will describe you how to generate alert
in selenium IDE software testing tool using "runScript" command with example.

Now let me describe you how to generate alert in selenium webdriver software
automation if required during test case execution of your software web
application.

Copy bellow given @Test method part of generate alert using javascript
example and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).

Example 3 : JavascriptExecutor to generate alert in selenium webdriver

@Test
public void test () throws InterruptedException
{
//Generating Alert Using Javascript Executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
Thread.sleep(2000);
driver.switchTo().alert().accept();
}

In above example, Java Script Executor will simply execute the javascript and
generate alert. You can your own alert text in it. Try it in your own software
application test if required.
Use Of isMultiple() And deselectAll() In
Selenium WebDriver With Example
Now you can easily select or deselect any specific option from select box or
drop down as described in my earlier POST 1, POST 2and POST 3. All these
three posts will describe you different alternative ways of selecting options from
list box or drop down. Now let me take you one step ahead to describe you the
use of deselectAll() and isMultiple() methods in selenium webdriver.

deselectAll() Method
deselectAll() method is useful to remove selection from all selected options of
select box. It will works with multiple select box when you need to remove all
selections. Syntax for deselectAll() method is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();

isMultiple() Method
isMultiple() method is useful to verify if targeted select box is multiple select box
or not means we can select multiple options from that select box or not. It will
return boolean (true or false) value. We can use it with if condition before working
with select box. Syntax is as bellow.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
System.out.print(value);

Bellow given example will show you use of isMultiple() and deselectAll()
methods very clearly in selenium webdriver.

@Test
public void test () throws InterruptedException
{
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));

//To verify that specific select box supports multiple select or not.
if(listbox.isMultiple())
{
System.out.print("Multiple selections is supported");
listbox.selectByVisibleText("USA");
listbox.selectByValue("Russia");
listbox.selectByIndex(5);
Thread.sleep(3000);

//To deselect all selected options.


listbox.deselectAll();
Thread.sleep(2000);
}
else
{
System.out.print("Not supported multiple selections");
}
}

In above example, if condition will check that listbox is multiple select box or
not? Used listbox.deselectAll(); to remove all selected options.

How To Deselect Option By Visible Text Or


Value Or By Index In Selenium WebDriver
With Example
Adding selection or removing selection from list box are very common actions
for list box. Selenium WebDriver has 3 alternate options to select or deselect
value from list box. It is very important to learn all three methods of selecting or
deselecting option from list box because if one is not possible to implement in
your test then you must be aware about alternate option. I already described 3
selection options in my earlier posts - Selecting specific option BY VISIBLE
TEXT, BY VALUE or BY INDEX from drop down or list box.
Now let me describe you all three deselect methods to deselect specific option
from list box. Do you remember that we can use "removeSelection" command to
deselect option from list box? VIEW THIS SELENIUM IDE EXAMPLE for
"removeSelection" command.

1. Deselect By Visible Text


If you wants to remove selection from list box then you can use
webdriver's deselectByVisibleText() method. Syntax is as bellow. 1st syntax will
locate the select box and 2nd syntax will remove selection by visible text
= Russia.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");

2. Deselect By Value
You can also deselect option from list box by value. 2nd syntax will deselect
option by value = Mexico.

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");

3. Deselect By Index
Bellow given syntax will remove selection by index = 5.

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);

Execute bellow given example in eclipse and observe results during execution.

Copy bellow given @Test method part of deselect option by visible text or
value or index and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that linked
page).

@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");

Select listbox = new


Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByVisibleText("USA");
listbox.selectByVisibleText("Russia");
Thread.sleep(1000);

//To deselect by visible text


listbox.deselectByVisibleText("Russia");
Thread.sleep(1000);

listbox.selectByValue("Japan");
listbox.selectByValue("Mexico");
Thread.sleep(1000);

//To deselect by value


listbox.deselectByValue("Mexico");
Thread.sleep(1000);

listbox.selectByIndex(4);
listbox.selectByIndex(5);
Thread.sleep(1000);

//To deselect by index


listbox.deselectByIndex(5);
Thread.sleep(1000);

driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(1000);
}
}
You can view MORE webdriver examples on THIS LINK.

How To Select Option By Value or By Index


In Selenium WebDriver With Example
In my earlier post, We have seen example of HOW TO SELECT OPTION BY
VISIBLE TEXT from drop down. There are two more alternatives to select
option value from drop down or list box in selenium webdriver software
testing tool. 1. Selecting Option By Value and 2. Selecting Option By Index.
You can use any one from these three to select value from list box of your
software web application page. If you know, we can use "select" command or
"addSelection" command in selenium IDE software testing tool to select option
from list box.

First of all let me show you difference between visible text, value and index of
list box option. Bellow given image will show you clear difference between value,
visible text and index.
1. Select Option By Value In WebDriver
Syntax for selecting option by value in webdriver is as bellow. First syntax will
locate the select element from page of software web application and 2nd syntax
will select the option from select box by value = Italy.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");

2. Select Option By Index In WebDriver


Syntax for selection option by index from list box is as bellow. It will select 1st
element(index = 0) from select box of software web application page.
Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
Execute bellow given example in your eclipse and verify result. Try to use it in
different applications.

Copy bellow given @Test method part of select option by value or index and
replace it with the @Test method part of example given on THIS PAGE.(Note
: @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");

//Selecting value from drop down by value


Select listbox = new
Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
listbox.selectByValue("Mexico");
listbox.selectByValue("Spain");

driver.findElement(By.xpath("//input[@value='->']")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));

//Selecting value from drop down by index


listbox.selectByIndex(0);
listbox.selectByIndex(3);
driver.findElement(By.xpath("//input[@value='->']")).click();
Thread.sleep(2000);
}

Selenium Webdriver tutorial : How To Select


Dropdown Value With Example
In my earlier tutorial of selenium webdriver software testing tool, we learn few
basic action commands of selenium WebDriver like HOW TO CLICK ON
BUTTON, IMPLICIT WAIT, EXPLICIT WAIT etc. THIS LINK will show
you more different examples of basic action commands of selenium webdriver
software testing tool. As you know, Drop down is also essential element of any
software web application page. So it is important to know that how to control
or take action on drop down list like selecting specific value from drop down
list using selenium webdriver/selenium 2.

Create selenium webdriver data driven framework from scratch @This Page.

If you know, In selenium IDE software testing tool we can select value from drop
down list using "select" or "addSelection" command. Now let me give you
example of how to select value from drop down list in webdriver.

In bellow given example, First imported webdriver package


"org.openqa.selenium.support.ui.Select" to get support of webdriver class
"Select".
import org.openqa.selenium.support.ui.Select;

Now we can use "Select" class to identify drop down from web page by writing
bellow given syntax.

Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));

Now we can select any value from selected drop down as bellow.

mydrpdwn.selectByVisibleText("Audi");

Full Example to select value from drop down of software applications's web
page is as bellow.

EXAMPLE

package junitreportpackage;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Mytesting {


WebDriver driver = new FirefoxDriver();

@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}

@After
public void aftertest() {
driver.quit();

@Test
public void test () throws InterruptedException
{
driver.findElement(By.id("text1")).sendKeys("My First Name");

//Selecting value from drop down using visible text


Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
}

}
Same thing we can do for list box to select option from list box by visible text.
View my previous post to know how to select value by index from drop down.

Selenium WebDriver : How To Navigate


URL, Forward and Backward With Example
In my earlier posts, we have learnt few BASIC ACTION
COMMANDS of selenium WebDriver software testing tool with examples.
You will have to use them on daily basis for you software web application's
webdriver test case preparation. It is very important for you to use them on right
time and right place. Now let we learn 3 more action commands of webdriver.

1. driver.navigate().to
If you wants to navigate on specific software web application page or URL in
between your software test then you can use driver.navigate().to command as
bellow.
driver.navigate().to("http://only-testing-
blog.blogspot.com/2014/01/textbox.html");

2. driver.navigate().back();
This command is useful to go back on previous page. Same as we are clicking
browser back button. You can use this command as bellow. In Selenium IDE
software testing tool, we can use "goBack" to perform same action.
driver.navigate().back();

3. driver.navigate().forward();
Same as we are clicking on forward button of browser.

Bellow given example will cover all three commands. Execute it in your eclipse
to know them practically.
Copy bellow given @Test method part of driver.navigate() command examples
and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).

@Test
public void test () throws InterruptedException
{
driver.navigate().to("http://only-testing-
blog.blogspot.in/2014/01/textbox.html");

//To navigate back (Same as clicking on browser back button)


driver.navigate().back();

//To navigate forward (Same as clicking on browser forward button)


driver.navigate().forward();
}

Selenium WebDriver : Verify Element


Present In Selenium WebDriver
Some times you need to verify the presence of element before taking some
action on software web application page. As you know, Selenium IDE has many
built in commands to perform different types of actions on your software web
application page. You can verify presence of element by using
"verifyElementPresent" command in selenium IDE software testing tool. Also
you can view example of selenium IDE software testing
tool's "verifyElementNotPresent" command. Web driver have not any built in
method or interface by which we can verify presence of element on the page of
software web application.

Yes we can do it very easily in WebDriver too using bellow given syntax.
Boolean iselementpresent =
driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;

We have to use findElements() method for this purpose. Above syntax will return
true if element is present on page of software web application. Else it will return
false. You can put if condition to take action based on presence of element on
page of software web application.

Bellow given example will check the presence of different text box on page. It
will print message in console based on presence of element.

Copy bellow given @Test method part of iselementpresent example and replace
it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).

@Test
public void test () throws InterruptedException
{
for (int i=1; i<6; i++)
{

//To verify element is present on page or not.


String XPath = "//input[@id='text"+i+"']";
Boolean iselementpresent = driver.findElements(By.xpath(XPath)).size()!=
0;
if (iselementpresent == true)
{
System.out.print("\nTargeted TextBox"+i+" Is Present On The Page");
}
else
{
System.out.print("\nTargeted Text Box"+i+" Is Not Present On The Page");
}
}
}

Selenium Webdriver Tutorial To Capture


Screenshot With Example
Capturing screenshot of software web application page is very easy in selenium
webdriver. As we knows, It is very basic required thing in software automation
tools to capture screenshot on test case failure or whenever required during test
case execution.VIEW MORE SELENIUM WEBDRIVER BASIC
COMMANDS for your webdriver knowledge improvement and use them in
your software web application test case creation.

If you remember, We can use "captureEntirePageScreenshot" command in


selenium IDE to capture the screenshot on software web application current page.
In Selenium WebDriver/Selenium 2, we need to capture screenshot of web page
using bellow syntax.
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

Then we have to store it in our local drive using bellow given syntax. You can
change/provide your own file destination path and name.
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));

Now we need to import bellow given header files to get support of capture
screenshot in webdriver.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

Copy bellow given @Test method part of Capture screen shot webdriver
example and replace it with the @Test method part of example given on THIS
PAGE. Don't forget to import above given header files in your eclipse
test.(Note : @Test method is marked with pink color in that linked page).

@Test
public void test () throws InterruptedException, IOException
{
//Capture entire page screenshot and then store it to destination drive
File screenshot =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
System.out.print("Screenshot is captured and stored in your D: Drive");
}

You can put above syntax under catch block of try to capture screenshot on
failure. You can view THIS POST If you wants to record video for your
selenium webdriver software test execution.

Selenium WebDriver : Generating Mouse


Hover Event On Main Menu To Click On
Sub Menu
Selenium WebDriver is totally freeware software testing tool and we can use it
for software web application regression purpose.Hovering mouse on main
menu or any other element of web page or simulating mouse movement in
webdriver is not very tough task. As you know, We can perform most of actions
and operations directly in webdriver software testing tool and you canVIEW
FEW OF THEM ON THIS PAGE. But there are also some actions which we
can not perform directly in webdriver and to perform them, we need to use some
tricky ways. Generating mouse hover event is one of them.

To generate mouse hover event in webdriver software testing tool, We can


use advanced user interactions API constructor "Actions" with "moveToElement"
method. Bunch of syntax to hover mouse on main menu is as bellow. You can
replace xpath of an element as per your requirement in bellow given syntax.

Actions actions = new Actions(driver);


WebElement moveonmenu =
driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();

Above example will only move mouse on targeted element of software web
application. It will not perform click operation. To perform click operation on
sub menu, we need to use click() action before perform() as shown in bellow
example.
package junitreportpackage;

import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Mytesting {


WebDriver driver = new FirefoxDriver();

@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/p/mouse-hover.html");
}

@After
public void aftertest() {
driver.quit();

@Test
public void test () throws InterruptedException, IOException
{

//Generate mouse hover event on main menu to click on sub menu


Actions actions = new Actions(driver);
WebElement moveonmenu =
driver.findElement(By.xpath("//div[@id='menu1']/div"));

actions.moveToElement(moveonmenu).moveToElement(driver.findElement(By.xpath("
//div[@id='menu1choices']/a"))).click().perform();

WebDriverWait wait = new WebDriverWait(driver, 15);


wait.until(ExpectedConditions.titleContains("Google"));
}

Example of Handling Multiple Browser


Windows in Selenium WebDriver
Selenium WebDriver software testing tool has built in
"WebDriver.switchTo().window()" method available to switch from one
window to another window so it is very easy to handle multiple windows in
webdriver. If you remember, We can use "selectWindow" window command in
selenium IDE software testing tool to select another window. If window do not
have any title or both window has same title then it was very difficult to select
other window in selenium IDE software testing tool. WebDriver software testing
tool has made it very easy. You can handle multiple windows even if all the
windows do not have any title or contains same title.

If you wants to work with multiple tabs then view THIS POST and wants to
work with multiple IFrames then view THIS POST.

WebDriver.getWindowHandles()
In WebDriver software testing tool, We can use
"WebDriver.getWindowHandles()" to get the handles of all opened windows by
webdriver and then we can use that window handle to switch from from one
window to another window. Example Syntax for getting window handles is as
bellow.

Set<String> AllWindowHandles = driver.getWindowHandles();


WebDriver.switchTo().window()
WebDriver.switchTo().window() method is useful to switch from one window
to another window of software web application. Example syntax is as bellow.

driver.switchTo().window(window2);

Bellow given webdriver example of switching window will explain you it


deeply. Execute it in your eclipse and try to understand how webdriver do it.

Copy bellow given @Test method part of handling multiple windows of


webdriver and replace it with the @Test method part of example given on THIS
PAGE.(Note : @Test method is marked with pink color in that linked page).

@Test
public void test () throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//b[contains(.,'Open New Page')]")).click();

// Get and store both window handles in array


Set<String> AllWindowHandles = driver.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code = "+AllWindowHandles.toArray()[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code = "+AllWindowHandles.toArray()[1]);

//Switch to window2(child window) and performing actions on it.


driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
driver.findElement(By.xpath("//input[@value='Bike']")).click();
driver.findElement(By.xpath("//input[@value='Car']")).click();
driver.findElement(By.xpath("//input[@value='Boat']")).click();
driver.findElement(By.xpath("//input[@value='male']")).click();
Thread.sleep(5000);
//Switch to window1(parent window) and performing actions on it.
driver.switchTo().window(window1);
driver.findElement(By.xpath("//option[@id='country6']")).click();
driver.findElement(By.xpath("//input[@value='female']")).click();
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
driver.switchTo().alert().accept();
Thread.sleep(5000);

//Once Again switch to window2(child window) and performing actions on it.


driver.switchTo().window(window2);
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("Name
Changed");
Thread.sleep(5000);
driver.close();

//Once Again switch to window1(parent window) and performing actions on it.


driver.switchTo().window(window1);
driver.findElement(By.xpath("//input[@value='male']")).click();
Thread.sleep(5000);

How To Verify Element Is Enabled Or


Disabled in Selenium WebDriver
During your Selenium WebDriver software testing test case creation, frequently
you need to verify that your targeted element is enabled or disabled on page of
software web application before performing action on it. Webdriver has built in
method isEnabled() to check the element enable status on software web
application's page. Verification of element is disable and verification of element
invisible is totally different for any software web application.
Element is disabled means it is visible but not editable and element is invisible
means it is hidden. VIEW THIS EXAMPLE to know how to wait till element
is visible on the page of software web application.

isEnabled()
isEnabled() webdriver method will verify and return true if specified element is
enabled. Else it will return false. Generic syntax to store and print element's status
value is as bellow.
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);

We can use isEnabled() method with if condition to take action based on element's
enabled status on page of software web application. Bellow given example will
explain you deeply about isEnabled() webdriver method. If you are using
selenium IDE software testing tool then VIEW THIS POST to know how to wait
for targeted element becomes editable.

Copy bellow given @Test method part of check element enabled status and
replace it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).

@Test
public void test () throws BiffException, IOException, InterruptedException
{
boolean fname =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);

WebElement firstname =
driver.findElement(By.xpath("//input[@name='fname']"));
WebElement lastname =
driver.findElement(By.xpath("//input[@name='lname']"));

//Verify First name text box is enabled or not and then print related
message.
if(firstname.isEnabled())
{
System.out.print("\nText box First name is enabled. Take your action.");
}
else
{
System.out.print("\nText box First name is disabled. Take your action.");
}

//Verify Last name text box is enabled or not and then print related
message.
if(lastname.isEnabled())
{
System.out.print("\nText box Last name is enabled. Take your action.");
}
else
{
System.out.print("\nText box Last name is disabled. Take your action.");
}
}

Above given example, will check the status of First name and Last name text box
and print message in console based on element is enabled or disabled.

How To Enable/Disable Textbox In Selenium


WebDriver On The Fly
We can know element's enabled/disabled status very easily using isEnabled()
method in selenium webdriver software test as described in THIS EXAMPLE
POST. Now supposing you have a scenario where you wants to enable any
disabled text box or disable any enabled text box during software test execution
then how to do it? Webdriver do not have any built in method by which you
perform this action. But yes, Webdriver has JavascriptExecutor interface by
which we can execute any javascript using executeScript() method.

I have posted many posts on how to execute javascript in selenium webdriver


software testing tool to perform different actions. You can view all those example
on THIS LINK. Same way, we can enable or disable any element
using JavascriptExecutor interface during webdriver software test case execution.
To disable text box, we will use html dom setAttribute() method and to enable
text box, we will use html dom removeAttribute() method with executeScript()
method. Javascript syntax for both of these is as bellow.
document.getElementsByName('fname')[0].setAttribute('disabled', '');
document.getElementsByName('lname')[0].removeAttribute('disabled');

Now let we use both these javascripts practically to understand them


better. VIEW THIS POST to see how to enable or disable text box in selenium
IDE software testing tool.

Copy bellow given @Test method part of enable or disable element and replace
it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).

@Test
public void test () throws BiffException, IOException, InterruptedException
{
boolean fbefore =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nBefore : First Name Text box enabled status is :
"+fbefore);
boolean lbefore =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nBefore : Last Name Text box enabled status is :
"+lbefore);

Thread.sleep(2000);

//To disable First Name text box


JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable =
"document.getElementsByName('fname')[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
Thread.sleep(2000);

//To enable Last Name text box


String toenable =
"document.getElementsByName('lname')[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
Thread.sleep(3000);

boolean fafter =
driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print("\nAfter : First Name Text box enabled status is :
"+fafter);
boolean lafter =
driver.findElement(By.xpath("//input[@name='lname']")).isEnabled();
System.out.print("\nAfter : Last Name Text box enabled status is :
"+lafter);

Selenium WebDriver : Handling Javascript


Alerts, Confirmations And Prompts
Alerts, Confirmation and Prompts are very commonly used elements of any
software webpage and you must know how tohandle all these popups In
selenium webdriver software automation testing tool. If you know, Selenium
IDE has many commands to handle alerts, confirmations and prompt popups
likeassertAlert, assertConfirmation, storeAlert, verifyAlertPresent, etc.. First
of all, Let me show you all three different popup types to remove confusion from
your mind and then we will see how to handle them In selenium webdriver.

Alert Popup
Generally alert message popup display on page of software web application with
alert text and Ok button as shown In bellow given Image.
Confirmation Popup
Confirmation popup displays on page of software web application with
confirmation text, Ok and Cancel button as shown In bellow given Image.

Prompt Popup
Prompts will have prompt text, Input text box, Ok and Cancel buttons.

Selenium webdriver software testing tool has Its own Alert Interface to handle all
above different popups. Alert Interface has different methods like accept(),
dismiss(), getText(), sendKeys(java.lang.String keysToSend) and we can use all
these methods to perform different actions on popups.

VIEW WEBDRIVER EXAMPLES STEP BY STEP


Look at the bellow given simple example of handling alerts, confirmations and
prompts In selenium webdriver software automation testing tool. Bellow given
example will perform different actions (Like click on Ok button, Click on cancel
button, retrieve alert text, type text In prompt text box etc..)on all three kind of
popups using different methods of Alert Interface.

Run bellow given example In eclipse with testng and observe the result.

package Testng_Pack;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class unexpected_alert {


WebDriver driver;

@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

@Test
public void Text() throws InterruptedException {
//Alert Pop up Handling.
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
//To locate alert.
Alert A1 = driver.switchTo().alert();
//To read the text from alert popup.
String Alert1 = A1.getText();
System.out.println(Alert1);
Thread.sleep(2000);
//To accept/Click Ok on alert popup.
A1.accept();

//Confirmation Pop up Handling.


driver.findElement(By.xpath("//button[@onclick='myFunction()']")).click();
Alert A2 = driver.switchTo().alert();
String Alert2 = A2.getText();
System.out.println(Alert2);
Thread.sleep(2000);
//To click On cancel button of confirmation box.
A2.dismiss();

//Prompt Pop up Handling.


driver.findElement(By.xpath("//button[contains(.,'Show Me
Prompt')]")).click();
Alert A3 = driver.switchTo().alert();
String Alert3 = A3.getText();
System.out.println(Alert3);
//To type text In text box of prompt pop up.
A3.sendKeys("This Is John");
Thread.sleep(2000);
A3.accept();
}
}

This way you can handle different kind of alerts very easily using Alert
Interface of selenium webdriver software automation testing tool. Next post will
show you how to handle unexpected alerts In selenium webdriver.

How To Handle Unexpected Alerts In


Selenium WebDriver
Some times when we browsing software web application, Display
some unexpected alerts due to some error or some other reasons. This kind
of alerts not display every time but they are displaying only some time. If you
have created webdriversoftware automation test case for such page and not
handled this kind of alerts In your code then your script will fail Immediately If
such unexpected alert pop up displayed.

We have already learnt, How to handle expected alert popups In selenium


webdriver software testing tool In THIS EXAMPLE. Now unexpected alert
appears only some times so we can not write direct code to accept or dismiss that
alert. In this kind of situation, we have to handle them specially.

You can VIEW ALL WEBDRIVER TUTORIALS ONE BY ONE.

To handle this kind of unexpected alerts, You must at least aware about on which
action such unexpected alert Is generated. Sometimes, They are generated during
software web application page load and sometime they are generated when you
perform some action. So first of all we have to note down the action where such
unexpected alert Is generated and then we can check for alert after performing
that action. We need to use try catch block for checking such unexpected alters
because If we will use direct code(without try catch) to accept or dismiss alert
and If alert not appears then our test case will fail. try catch can handle both
situations.

I have one example where alert Is displaying when loading software web page.
So we can check for alert Inside try catch block after page load as shown In bellow
given example. After loading page, It will check for alert. If alert Is there on the
page then It will dismiss It else It will go to catch block and print message as
shown In bellow given example.

Run bellow given example In eclipse with testng and observe the result.

package Testng_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class unexpected_alert {


WebDriver driver;

@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/06/alert_6.html");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

@Test
public void Text() throws InterruptedException {
//To handle unexpected alert on page load.
try{
driver.switchTo().alert().dismiss();
}catch(Exception e){
System.out.println("unexpected alert not present");
}

driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("fname");
driver.findElement(By.xpath("//input[@name='lname']")).sendKeys("lname");
driver.findElement(By.xpath("//input[@type='submit']")).click();
}
}
Above given webdriver code Is just for example. It Is just explaining the way of
using try catch block to handle unexpected alert. You can use such try catch block
In that area where you are facing unexpected alerts very frequently.

How to highlight element using selenium


webdriver
As we have seen in my previous posts, we can Get Page Title, Get Domain
Name, Generate Alert using java script executorinterface of selenium
webdriver software testing tool. Using webdriver, we can perform many
different actions on software web page but for that you should be aware about
this kind of things. We can execute any other java scripts too using this interface
of webdriver.

Let me give you one more practical example for the same. Sometimes if you want
tohighlight element of software web application page then you can use javascript
executor. If you remember, we were using "highlight" command in selenium IDE
tohighlight any element of web page.

If you VIEW WEBDRIVER EXAMPLE ON THIS POST, i have created


function named HighlightMyElement and written few syntax of javascript
executor. Now if i want to highlight any element of software web page then
simply i need to call that function as shown in bellow example. You can change
your preferred highlighting color in that example.

Copy bellow given @Test method part of generate alert using javascript
example and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).

HighlightMyElement(driver.findElement(By.xpath("//input[@name='fname']")));
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
HighlightMyElement(driver.findElement(By.xpath("//button[@onclick='myFunction
()']")));
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton")));
HighlightMyElement(driver.findElement(By.cssSelector("#submitButton")));
driver.findElement(By.cssSelector("#submitButton")).click();

In above example, HighlightMyElement will highlight the all 3 targeted


elements on software web page by calling function.

Reading Font Properties In Selenium


WebDriver Using .getCssValue() Method
Sometimes you need to read font properties like font size, font color, font
family, font background color etc.. during WebDriver test case
execution. Selenium WebDriver Is very wast API and It has many built In
methods to perform very small small operations on web page. Reading font
property manually Is very simple task using firebug as shown In bellow given
Image.

If you wants to read above shown font property In selenium webdriver then you
can do It using .getCssValue() Method. You can provide property name (Example
: font-family, font-size, font-weight, etc.) with .getCssValue() method to read Its
value.

READ MORE TUTORIALS on selenium WebDriver.

Bellow given example will read values of font-size, color, font-family and text-
align properties of "Example Login Page" text.
package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class fontTest {


WebDriver driver = null;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://only-testing-
blog.blogspot.in/2014/05/login.html");
}

@Test
public void readFontProperty(){
//Locate text string element to read It's font properties.
WebElement text = driver.findElement(By.xpath("//h1[contains(.,'Example
Login Page')]"));

//Read font-size property and print It In console.


String fontSize = text.getCssValue("font-size");
System.out.println("Font Size -> "+fontSize);
//Read color property and print It In console.
String fontColor = text.getCssValue("color");
System.out.println("Font Color -> "+fontColor);

//Read font-family property and print It In console.


String fontFamily = text.getCssValue("font-family");
System.out.println("Font Family -> "+fontFamily);

//Read text-align property and print It In console.


String fonttxtAlign = text.getCssValue("text-align");
System.out.println("Font Text Alignment -> "+fonttxtAlign);
}
}

Output of above example Is as bellow.

Font Size -> 26.4px


Font Color -> rgba(102, 102, 102, 1)
Font Family -> "Trebuchet MS",Trebuchet,Verdana,sans-serif
Font Text Alignment -> left

You can use .getCssValue() method to get any other property value of any
element.

How to use implicit wait in selenium


webdriver and why
There are 2 types of waits available in Webdriver/Selenium 2 software testing
tool. One of them is Implicit wait and another one is explicit wait. Both (Implicit
wait and explicit wait) are useful for waiting in WebDriver. Using waits, we are
telling WebDriver to wait for a certain amount of time before going to next step.
We will see about explicit wait in my upcoming posts. In this post let me tell you
why and how to use implicit wait in webdriver.

Why Need Implicit Wait In WebDriver


As you knows sometimes, some elements takes some time to appear on software
web application page when browser is loading the page. In this case, sometime
your webdriver test will fail if you have not applied Implicit wait in your test case.
If implicit wait is applied in your test case then webdriver will wait for specified
amount of time if targeted element not appears on page. As you know, we can Set
default timeout or use"setTimeout" command in selenium IDE which is same
as implicit wait in webdriver.

If you write implicit wait statement in you webdriver software testing script then
it will be applied automatically to all elements of your test case. I am suggesting
you to use Implicit wait in your all test script of software web application with 10
to 15 seconds. In webdriver, Implicit wait statement is as bellow.

How To Write Implicit Wait In WebDriver

driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

Above statement will tell webdriver to wait for 15 seconds if targeted element not
found/not appears on page. Le we look at simple example to understand implicit
wait better.

Copy bellow given @Test method part and replace it with the @Test method
part of example given on this page. (Note : @Test method is marked with pink
color in that example).

@Test
public void test ()
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
driver.findElement(By.xpath("//input[@name='namexyz']"));
}
In Above webdriver test case with JUnit example, 1st Element
'xpath("//input[@name='fname']")' will be found on page but element
xpath("//input[@name='namexyz']") is not there on page. So in this case
webdriver will wait for 15 to locate that element on page because we have written
implicit wait statement in our code. At last webdriver test will fail because
xpath("//input[@name='namexyz']") is not on the page.

How to wait for element to be clickable in


selenium webdriver using explicit wait
In my previous post, We have seen how to wait implicitly in selenium webdriver
software testing tool. Let me remind you one thing is implicit wait will be applied
to all elements of test case by default while explicit will be applied to targeted
element only. This is the difference between implicit wait and explicit wait.
Still I am suggesting you to use implicit wait in your test script.

If you knows, In selenium IDE software testing tool we can use


"waitForElementPresent" or "verifyElementPresent" to wait for or verify that
element is present or not on software web application page. In selenium
webdriver, we can do same thing using explicit wait
of elementToBeClickable(By locator). Full syntax is as bellow.

Read more tutorials on selenium WebDriver @Tutorials Part 1 and @Tutorials


Part 2.

WebDriverWait wait = new WebDriverWait(driver, 15);


wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton")));

Here above syntax will wait till 15 seconds to become targeted


element(#submitButton) clickable if it is not clickable or not loaded on the page
of software web application. As soon as targeted element becomes clickable on
the page of software web application, webdriver will go for perform next action.
You can increase or decrease webdriver wait time from 15.

Let me give you practical example for the element to be clickable.


package junitreportpackage;

import java.util.concurrent.TimeUnit;
import java.io.FileInputStream;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Mytest1 {


WebDriver driver = new FirefoxDriver();

@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}

@After
public void aftertest() {
driver.quit();

}
@Test
public void test ()
{

driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My
Name");
//Wait for element to be clickable
WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton")));

driver.findElement(By.cssSelector("#submitButton")).click();
}
public void HighlightMyElement(WebElement element) {
for (int i = 0; i < 10; i++)
{
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: orange; border: 4px solid orange;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: pink; border: 4px solid pink;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "color: yellow; border: 4px solid yellow;");
javascript.executeScript("arguments[0].setAttribute('style',
arguments[1]);", element, "");
}
}
}

Run above given example of wait for element to be clickable in selenium


webdriver in your eclipse with junit. Click here to view different posts on how
to use junit with eclipse for your webdriver test.

WebDriver - wait for text to be present with


example using explicit wait
Some times you need to wait for text, wait for element, wait for alert before
performing actions in your regular software web application test cases
of selenium webdriver. Generally we need to use this types of conditions in our
test case when software web application page is navigating from one page to other
page. In my previous post, we have seen how to write and use wait for
element syntax in our test case. Now let we see how can we force webdriver to
wait if expected text is not displayed on targeted element of software web
application page.

As you know, we can use "waitForText" or "waitForTextPresent" commands


in selenium IDE software testing tool to wait till targeted text appears on page of
software web application or element. In webdriver, we can use syntax as shown
bellow.

WebDriverWait wait = new WebDriverWait(driver, 15);


wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div
[@id='timeLeft']"), "Time left: 7 seconds"));

Look in to above syntax. Here i have


used textToBePresentInElementLocated(By, String) to wait till expected text
appears on targeted element. So here what WebDriver will do is it will check for
expected text on targeted element on every 500 milliseconds and will execute
next step as soon as expected text appears on targeted element.

Run bellow given practical example.in eclipse and see how it works.
Copy bellow given @Test method part of wait for text example and replace it
with the @Test method part of example given on this page. (Note : @Test
method is marked with pink color in that linked page).

@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("alpesh");
WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#submitBut
ton1")));
driver.findElement(By.cssSelector("#submitButton")).click();

wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div
[@id='timeLeft']"), "Time left: 7 seconds"));
}

In above example, When WebDriver clicks on #submitButton page of software


web application will be refreshed and then WebDriver will wait for text = "Time
left: 7 seconds" on targeted element.

WebDriver how to wait for alert in selenium


2
As we have seen in my previous posts, we can
use textToBePresentInElementLocated(By, String) WebDriver condition to wait
for text present on page and we can use elementToBeClickable(By locator)
to wait for element clickable/present on page. If you read both those posts, We
had used explicit waits in both the cases and both are canned expected
conditions of webdriver so we can use them directly in our test case without any
modifications.

Sometimes you will face wait for alert scenario where you have to wait for
alert before performing any action on your software application web page. If you
know, we can use "waitForAlert" command in selenium IDE to handle alerts.
In WebDriver/Selenium 2, You can use WebDriver's built in canned condition
alertIsPresent() with wait command as bellow.

WebDriverWait wait = new WebDriverWait(driver, 15);


wait.until(ExpectedConditions.alertIsPresent());

Look in to above syntax. 1st syntax described how much time it has to wait and
2nd syntax describes the waiting condition. Here we have used alertIsPresent()
condition so it will wait for the alert on page. Let me give you full practical
example to describe scenario perfectly.
Copy paste bellow given test case in your eclipse with JUnit and then run it. You
can View how to configure eclipse with JUnit if you have no idea.

package junitreportpackage;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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;

public class Mytest1 {


WebDriver driver = new FirefoxDriver();

@Before
public void beforetest() {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/01/new-
testing.html");
}

@After
public void aftertest() {
driver.quit();

@Test
public void test ()
{
driver.findElement(By.xpath("//input[@name='fname']")).sendKeys("My Name");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
String alrt = driver.switchTo().alert().getText();
System.out.print(alrt);
}

Above example will wait for the alert on page and as soon as alert appears on
page, it will store alert text in variable 'alrt' and then will print to it in console.

Selenium WebDriver : How to wait till


element visible or appear or present on page
In any software web application's webdriver test case, you can easily wait for
presence of element using IMPLICIT WAIT. If you have used implicit wait in
your test case then you do not require to write any extra conditional statement to
wait for element visibility. But in some cases, if any element is taking too
much time to be visible on software web page then you can use EXPLICIT
WAIT condition in your test case.

If you have a scenario to wait till element visible on software web page
then selenium webdriver/Selenium 2 has its own method
named visibilityOfElementLocated(By locator) to check the visibility of element
on software web page. We can use this method with explicit webdriver wait
condition to wait till element visible of present on page. However, we can wait
for element to be clickable using elementToBeClickable(By locator) method as
described in THIS ARTICLE.

Syntax to wait till element visible on page is as bellow. It will wait max 15
seconds for element. As soon as element visible on page, webdriver will go for
executing next statement.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@i
d='text3']")));

Here is practical example of wait for element visible. Execute it once and then
use it for your software web application test scenario.

Copy bellow given @Test method part of wait for visibility of element
located example and replace it with the @Test method part of example given
on THIS PAGE.(Note : @Test method is marked with pink color in that linked
page).

@Test
public void test () throws InterruptedException, IOException
{
//To wait for element visible
WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@i
d='text3']")));

driver.findElement(By.xpath("//input[@id='text3']")).sendKeys("Text box is
visible now");
System.out.print("Text box text3 is now visible");

How to apply wait in webdriver till element


becomes invisible or hidden
As you know, WebDriver is software web application regression testing tool and
you will face many problems during yourwebdriver test case creation and
execution. You must knows alternate solution if one not works for your software
automation test scenario. For example, you have used IMPLICIT WAIT in your
software automation test case but if it is not sufficient to handle your condition
of waiting till element becomes invisible from page then you can use it's
alternative way of using EXPLICIT WAIT in your test case.
In my PREVIOUS POST, I have describe use
of visibilityOfElementLocated(By locator)method with explicit wait to wait till
element becomes visible (not hidden) on software web application page. Now let
we look at opposite side. If you wants webdriver to wait till element becomes
invisible or hidden from page then we can use invisibilityOfElementLocated(By
locator) method with wait condition.

Syntax for wait till element invisible from page is as bellow.

WebDriverWait wait = new WebDriverWait(driver, 15);


wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//input[
@id='text4']")));

In above syntax, you can change webdriver wait time from 15 to 20, 30 or more
as per your requirement. Also you can use anyOTHER ELEMENT
LOCATING METHODS except By.xpath. Practical example of webdriver wait
till element becomes invisible is as bellow.

Copy bellow given @Test method part of wait till element invisible and replace
it with the @Test method part of example given on THIS PAGE.(Note : @Test
method is marked with pink color in that linked page).

@Test
public void test () throws InterruptedException, IOException
{
//Wait for element invisible
WebDriverWait wait = new WebDriverWait(driver, 15);

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//input[
@id='text4']")));

System.out.print("Text box text4 is now invisible");


}
You can VIEW EXAMPLE OF "waitForElementNotPresent" IN
SELENIUM IDE if you are using selenium IDE.

Selenium WebDriver : Difference Between


findElement and findElements with example
We have seen many examples of webdriver's findElement() in my previous
posts. You will find syntax of findElement() with example on THIS PAGE if
you wants to use it in your software web application test case. Selenium
WebDriver software testing tool has one more related method findElements.
Now main question is what is the difference
between findElement and findElements methods in selenium 2 software
automation tool? First of all let me provide you difference description and then
example.

findElement() method
 We need to use findElement method frequently in our webdriver software
test case because this is the only way to locate any element in webdriver software
testing tool.
 findElement method is useful to locating targeted single element.
 If targeted element is not found on the page then it will
throw NoSuchElementException.
findElements() method
 We are using findElements method just occasionally.
 findElements method will return list of all the matching elements from
current page as per given element locator mechanism.
 If not found any element on current page as per given element locator
mechanism, it will return empty list.
Now let me provide you simple practical example of findElement method and
findElements method to show you clear difference. You can VIEW ALL
PRACTICAL EXAMPLES OF SELENIUM WEBDRIVER one by one.

Copy bellow given @Test method part of findElement and findElements method
examples and replace it with the @Test method part of example given on THIS
PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
WebElement option =
driver.findElement(By.xpath("//option[@id='country5']"));
System.out.print(option.getAttribute("id")+" - "+option.getText());
List<WebElement> options= driver.findElements(By.xpath("//option"));
System.out.println(options.size());
for(int i=0;i<=options.size();i++)
{
String str = options.get(i).getAttribute("id")+" -
"+options.get(i).getText();
System.out.println(str);

In above example, findElement will locate only targeted element and then print
its id and text in console while findElements will locate all those elements of
current page which are under given xpath = //option. for loop is used to print all
those element's id and text in console.

Same way you can locate all input elements, link elements etc..
using findElements method.

How To Generate And Insert Log In


Selenium Webdriver Using log4j Jar
Assume you have prepared test case for your software web application test
scenario (using selenium webdriver with eclipse and junit) and now you
wants generate log file to insert your execution time log messages in to it. How
you will do it? Selenium webdriver software testing tool don't have any built in
function or method to generate log file. In this case you can use apache logging
service. Let me describe you steps to generate log file in selenium
webdriver test for software web application.

Steps To Generate And Insert Log In Selenium Webdriver

1. Download log4j jar file from logging.apache.org


 Click Here to go to log4j jar file downloading page. (This Link URL may
change in future).
 Click on Zip folder link as shown in bellow image. Current version
of log4j jar file is log4j-1.2.17. Version of log4j jar file may be different in
future due to the frequent version change.

 When you click on zip folder link, it will show you zip mirror links to
download folder. Download and save zip folder by clicking on mirror link.
 Now Extract that zip folder and look inside that extracted folder. You will
find log4j-1.2.17.jar file in it.
2. Import log4j-1.2.17.jar file in your eclipse project from
 Right click on your project folder and go to Build Path -> Configure
Build path. It will open java build path window as shown in bellow image.

 Click on Add External JARs button and select log4j-1.2.17.jar file. It will
add log4j-1.2.17.jar file in your build path.
 Click on OK button to close java build path window.
3. Create Properties folder under your project folder and
add log4j.properties file in it.
 Create folder with name = Properties under your project by right clicking
on your project folder.
 Click Here to download log4j.properties file and save it in Properties
folder which is created under your project folder.
 Now your properties folder under project folder will looks like bellow.

4. Set Run Configuration


This is optional step. You need to set your Run configure if log file is not
generated and display bellow given warning message in your console when you
run your test case.
log4j:WARN No appenders could be found for logger (dao.hsqlmanager).
 Go to Run -> Run Configurations -> Classpath
 Select User Entries -> Click on 'Advanced' button -> Select Add Folder ->
And then select Properties folder from your project and click on OK. Now your
Class tab will looks like bellow.
5. Create example(Sample) test case under your project.
Create your own test case or copy example test case from here and paste it in
your class file.

6. Import log4j header file in your project


Import bellow given header file in your test case class file.
import org.apache.log4j.*;

7. Replace bellow given syntax in your class file and Run your test case.

@Test
public void test () throws InterruptedException
{
Logger log;
driver.findElement(By.id("text1")).sendKeys("My First Name");
log = Logger.getLogger(Mytesting.class);
log.info("Type In Text field.");
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
log = Logger.getLogger(Mytesting.class);
log.info("Select value from drop down.");
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text2")));
}

When your test case for software web application is executed, Go to folder
= C:\Logs. log.log file will be created over there. Open that file and look in to it.
Log written in your software test case will be inserted in your log file. In above
example, Syntax marked with Pink color are written for inserting log. Now you
can write log at any place in your test case of software web application as shown
in above example.

Creating Object Repository Using Properties


File In Selenium WebDriver
In selenium WebDriver software automation testing tool, There Is not any built
In facility to create object repository. So maintenance of page objects(Page
element locators) becomes very hard If you will write all objects of page on code
level. Let me give you one simple example - You have one search button on page
of software web application and you have used It(Using Id locator) In many of
your test cases. Now supposing someone has changed Its Id In your application
then what you will do? You will go for replacing Id of that element In all test
cases wherever It Is used? It will create overhead for you. Simple solution to
remove this overhead Is creating object repository using properties
File support of java software development language. In properties file, First we
can write element locator of software web element and then we can use It In our
test cases.

Let us try to create object repository for simple calculator application given
on THIS PAGE and then will try to create test case for that calc software
application using object repository..

How to create new properties file


To create new properties file, Right click on your project package -> New ->
Other .
It will open New wizard. Expand General folder In New wizard and
select File and click on Next button.

Give file name objects.properties on next window and click on Finish button.
It will add object.properties file under your package. Now copy paste bellow
given lines in objects.properties file. So now this objects.properties file Is object
repository for your web application page calc.

objects.properties file
#Created unique key for Id of all web elements.
# Example 'one' Is key and '1' Is ID of web element button 1.
one=1
two=2
three=3
four=4
five=5
six=6
seven=7
eight=8
nine=9
zero=0
equalsto=equals
cler=AC
result=Resultbox
plus=plus
minus=minus
mul=multiply

In above file, Left side value Is key and right side value Is element locator(by Id)
of all web elements of web calculator. You can use other element locator methods
too like xpath, css ect.. VISIT THIS LINK to view different element locator
methods of webdriver.

Now let us create webdriver test case to perform some operations on calculation.
In bellow given example, All the element locators are coming from
objects.properties file using obj.getProperty(key). Here key Is reference of
element locator value in objects.properties file.
package ObjectRepo;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class CalcTest {


WebDriver driver = new FirefoxDriver();

@BeforeMethod
public void openbrowser() throws IOException {
driver.manage().window().maximize();
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}

@AfterMethod
public void closebrowser() {
driver.quit();
}

@Test
public void Calc_Operations() throws IOException{
//Create Object of Properties Class.
Properties obj = new Properties();
//Create Object of FileInputStream Class. Pass file path.
FileInputStream objfile = new
FileInputStream(System.getProperty("user.dir")+"\\src\\ObjectRepo\\objects.pr
operties");
//Pass object reference objfile to load method of Properties object.
obj.load(objfile);

//Sum operation on calculator.


//Accessing element locators of all web elements using obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("eight"))).click();
driver.findElement(By.id(obj.getProperty("plus"))).click();
driver.findElement(By.id(obj.getProperty("four"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String i =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("eight")+" + "+obj.getProperty("four")+"
= "+i);
driver.findElement(By.id(obj.getProperty("result"))).clear();

//Subtraction operation on calculator.


//Accessing element locators of all web elements using obj.getProperty(key)
driver.findElement(By.id(obj.getProperty("nine"))).click();
driver.findElement(By.id(obj.getProperty("minus"))).click();
driver.findElement(By.id(obj.getProperty("three"))).click();
driver.findElement(By.id(obj.getProperty("equalsto"))).click();
String j =
driver.findElement(By.id(obj.getProperty("result"))).getAttribute("value");
System.out.println(obj.getProperty("nine")+" - "+obj.getProperty("three")+"
= "+j);
}
}

Run above given example In your eclipse and observe execution.

Now supposing I have many such test cases and some one has changed Id of any
button of calc application then what I have to do? I have to modify all test cases?
Answer Is No. I just need to modify objects.properties file because I have not use
element's Id directly In any test case but I have Used just Its key reference In all
test cases.

This way you can create object repository of all your software web elements In
one .properties file. You can VIEW MORE TUTORIALS about selenium
webdriver.

How To Get/Extract All Links From Web


Page Using Selenium WebDriver
As we all knows, Each and every software web application contains many number
of different links/URLs. Some of them are redirecting to some page of same
website and others are redirecting to any external software web application. One
of my blog reader has requested the webdriver software test script example
for extracting all these links from page and print it in console using selenium
webdriver. I have created and published many different WEBDRIVER
EXAMPLE SCRIPTS on this blog but requested example by blog reader is not
pushed till now so I have created example for the same to share with all of you.

You can look at example of EXTRACTING TABLE DATA USING


SELENIUM WEBDRIVER.

We have seen HOW TO USE findElements in webdriver to locate multiple


elements of software web page. We can use same thing here to locate multiple
links of the page. Bellow given example will retrieve all URLs from the software
web page and will print all of them in console. You can click on each URL if you
wish to do so. Try bellow given example for different websites by providing that
website's URL in @Before annotation.

Copy bellow given @Test method part of extract all links from software web
page and replace it with the @Test method part of example given on THIS
PAGE.(Note : @Test method is marked with pink color in that linked page).

@Test
public void test () throws InterruptedException
{
try {
List<WebElement> no = driver.findElements(By.tagName("a"));
int nooflinks = no.size();
System.out.println(nooflinks);
for (WebElement pagelink : no)
{
String linktext = pagelink.getText();
String link = pagelink.getAttribute("href");
System.out.println(linktext+" ->");
System.out.println(link);
}
}catch (Exception e){
System.out.println("error "+e);
}

THIS LINK will show you many other basic action command examples. Have
you READ POST on how to find broken link from page?

Selenium WebDriver : Extracting All Text


Fields From Web Page
Sometimes you need to extract specific types of web elements from software
web page like extract all Links to open all of them one by one, extract all text
boxes from page to type some text In all of them or In some of them one by one.
Previously we have learnt how to extract all links from software web page
In THIS POST. Now supposing you have a scenario where you needs toextract
all text fields from software web page to send some text In all of them how to
do It In selenium WebDriver?

You can VIEW MORE TUTORIALS ON SELENIUM WEBDRIVER.

WebDriver's In built findelements method will help us to find all text boxes from
software web page. If you know, Each simple text box are Input fields and will
have always attribute type = text and If It Is password text box then It's type will
be password as shown In bellow given Image.
In short we have to find all those Input fields where type = "text" or "password".
In bellow given example, I have used findelements method to find and store all
those elements In txtfields array list and then used for loop to type some text In
all of them.

package Testng_Pack;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Extract_Text {


WebDriver driver;

@BeforeTest
public void StartBrowser() {
driver = new FirefoxDriver();
}

@Test
public void Text() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//find all input fields where type = text or password and store them In
array list txtfields.
List<WebElement> txtfields =
driver.findElements(By.xpath("//input[@type='text' or @type='password']"));

//for loop to send text In all text box one by one.


for(int a=0; a<txtfields.size();a++){
txtfields.get(a).sendKeys("Text"+(a+1));
}
Thread.sleep(3000);
}

@AfterTest
public void CloseBrowser() {
driver.quit();
}
}

This way we can extract all text box from software web page If required In any
scenario.

How To Extract Table Data/Read Table Data


Using Selenium WebDriver Example
Table Is very frequently used element In software web pages. Many times you
need to extract your web table data to compare and verify as per your test case
using selenium webdriver software testing tool. You can read about How To
Extracting All Links From Page If you need It In your test scenarios. If you
knows, Selenium IDE software testing tool has also many commands related to
Table and you can view all of them on LINK 1 and LINK 2 with examples. Now
let me come to our current discussion point about how to read values from
table of software web application. Before reading values from web table, You
must know there are how many rows and how many columns In your table. Let
we try to get number of rows and columns from table.
SELENIUM WEBDRIVER STEP BY STEP TUTORIALS.

How To Get Number Of Rows Using Selenium WebDriver

Look at the firebug view of above HTML table. In any web table, Number of <tr>
tags Inside <tbody> tag describes the number of rows of table. So you need to
calculate that there are how many <tr> tags Inside <tbody> tag. To get row count
for above given example table, we can use webdriver statement like bellow.

int Row_count = driver.findElements(By.xpath("//*[@id='post-body-


6522850981930750493']/div[1]/table/tbody/tr")).size();

In above syntax, .size() method with webdriver's findElements method will


retrieve the count of <tr> tags and store It In Row_count variable.

How To Get Number Of Columns Using Selenium WebDriver


Same way In any web table, Number of <td> tags from any <tr> tag describes the
number of columns of table as shown In bellow given Image.

So for getting number of columns, we can use syntax like bellow.

int Col_count = driver.findElements(By.xpath("//*[@id='post-body-


6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();

Now we have row count and column count. One more thing you require to read
data from table Is generating Xpath for each cell of column. Look at bellow given
xpath syntax of 1st cell's 1st and 2nd rows.

//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[2]/td[1]

Highlighted string Is common for both cell's xpath. Only changing Is row number
Inside tr node. So here we can pass Row_count variable's value Inside tr node.
Same way, look at bellow given xpath syntax of 1st and 2nd cells of 1st row.
Highlighted string Is common for both cell's xpath. Only changing Is column
number Inside td node. So here we can pass Col_count variable's value Inside td
node.

//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[1]
//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td[2]

All above thing Is applied In bellow given example. Simply run It In your eclipse
using testng and observe output In console.
package Testng_Pack;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class table {

WebDriver driver = new FirefoxDriver();


@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-
blog.blogspot.in/2013/09/test.html");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

@Test
public void print_data(){
//Get number of rows In table.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body-
6522850981930750493']/div[1]/table/tbody/tr")).size();
System.out.println("Number Of Rows = "+Row_count);

//Get number of columns In table.


int Col_count = driver.findElements(By.xpath("//*[@id='post-body-
6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();
System.out.println("Number Of Columns = "+Col_count);

//divided xpath In three parts to pass Row_count and Col_count values.


String first_part = "//*[@id='post-body-
6522850981930750493']/div[1]/table/tbody/tr[";
String second_part = "]/td[";
String third_part = "]";

//Used for loop for number of rows.


for (int i=1; i<=Row_count; i++){
//Used for loop for number of columns.
for(int j=1; j<=Col_count; j++){
//Prepared final xpath of specific cell as per values of i and j.
String final_xpath = first_part+i+second_part+j+third_part;
//Will retrieve value from located cell and print It.
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.print(Table_data +" ");
}
System.out.println("");
System.out.println("");
}
}
}

Console output of above given example will looks like bellow.

Number Of Rows = 3
Number Of Columns = 6
11 12 13 14 15 16

21 22 23 24 25 26

31 32 33 34 35 36
Here you can see, all the values of table are extracted and printed.

How To Handle Dynamic Web Table In


Selenium WebDriver
If web table has same number of rows and same number of cells In each rows
every time you load page then It Is very easy to handle that table's data
In selenium WebDriver software testing tool as described In How To Extract
Table Data/Read Table Data Using Selenium WebDriver post. Now
supposing your table's rows and columns are increasing/decreasing every time
you loading page of software web application or some rows has more cells and
some rows has less cells then you need to put some extra code In your webdriver
software test case which can retrieve cell data based on number of cells In
specific row. Consider the dynamic webtable shown In bellow given Image.

In this table, Row number 1, 2 and 4 has 3 cells, Row number 3 has 2 Cells and
Row 5 has 1 cell. In this case, You need to do some extra code to handle these
dynamic cells of different rows. To do It, You need to find out the number of cells
of that specific row before retrieving data from It.

You can view more webdriver software testing tutorials with testng and
java WEBDRIVER TUTORIAL @PART 1 and WEBDRIVER
TUTORIAL @PART 2.
Bellow given example will first locate the row and then It will calculate the cells
from that row and then based on number of cells, It will retrieve cell data
Information.

Run bellow given example In your eclipse with testng which Is designed for
above given dynamic web table.
package Testng_Pack;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class dynamic_table {


WebDriver driver = new FirefoxDriver();

@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

@Test
public void Handle_Dynamic_Webtable() {

//To locate table.


WebElement mytable = driver.findElement(By.xpath(".//*[@id='post-body-
8228718889842861683']/div[1]/table/tbody"));
//To locate rows of table.
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
//To calculate no of rows In table.
int rows_count = rows_table.size();

//Loop will execute till the last row of table.


for (int row=0; row<rows_count; row++){
//To locate columns(cells) of that specific row.
List<WebElement> Columns_row =
rows_table.get(row).findElements(By.tagName("td"));
//To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row "+row+" are "+columns_count);

//Loop will execute till the last cell of that specific row.
for (int column=0; column<columns_count; column++){
//To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column number
"+column+" Is "+celtext);
}
System.out.println("--------------------------------------------------");
}
}
}

Above example will works for dynamic changing web table too where number
of rows changing every time you load the page or search for something.

How To Create And Use Custom Firefox


Profile For Selenium WebDriver
What Is the Firefox Profile?
When you Install Firefox In your computer, Firefox creates one
default profile folder In your local drive to save your preferences like your
bookmarks, your preferred home page on Firefox open, your toolbar settings,
your saved passwords and all the other settings. You can create different profiles
for your Firefox browser as per your software testing requirement. Now
supposing same computer Is used by two users and both wants their own Firefox
settings then both users can create their own Firefox profile to access their own
settings when he/she opens Firefox browser.
You can LEARN SELENIUM WEBDRIVER STEP BY STEP to become
master of selenium Webdriver software testing tool.

If you have noticed, When you will run your selenium webdriver software
automation test In Firefox browser then WebDriver will open blank Firefox
browser like No bookmarks, No saved passwords, No addons etc.. as shown In
bellow given Image.

If you wants access of all these things In your selenium webdriver software
automation test browser then you have to create new profile of Firefox and set all
required properties In newly created profile and then you can access that profile
In webdriver using FirefoxProfile class of webdriver.

First Of all, Let us see how to create new profile of Firefox and then we will see
how to use that profile In your test.

How to Create New Custom Firefox Profile For Selenium WebDriver?


To create new firefox profile manually,

 Close Firefox browser from File -> Exit.


 Go to Start -> Run and type "firefox.exe -p" In run window and click OK.
It will open "Firefox - Choose User Profile" dialogue as shown In bellow Image.
 Now click on Create profile button. It will open create profile wizard
dialogue. Click On Next as shown In bellow given Image.

 On next screen, Give profile name = "WebDriver_Profile" and click on


finish button as shown In bellow given Image.
 It Will create new profile of Firefox.
 To use that newly Created profile, Select that profile and click on Start
Firefox button as shown In bellow given Image. It will open Firefox browser
with newly created profile.

Now you can make you required settings on this new created profile browser like
add your required addons, bookmark your required page, network settings, proxy
settings, etc.. and all other required settings.

How To Access Custom Firefox(Changing User Agent) Profile In Selenium


WebDriver Test
To access newly created Firefox profile In selenium WebDriver software test, We
needs to use webdriver's Inbuilt class ProfilesIni and Its method getProfile as
shown In bellow given example.

package Testng_Pack;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class custom_profile {


WebDriver driver;

@BeforeTest
public void StartBrowser() {
//Create object of webdriver's inbuilt class ProfilesIni to access Its
method getProfile.
ProfilesIni firProfiles = new ProfilesIni();
//Get access of newly created profile WebDriver_Profile.
FirefoxProfile wbdrverprofile =
firProfiles.getProfile("WebDriver_Profile");
//Pass wbdrverprofile parameter to FirefoxDriver.
driver = new FirefoxDriver(wbdrverprofile);
}

@Test
public void OpenURL(){
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
}

@AfterTest
public void CloseBrowser() {
driver.quit();
}
}

When you will run above given example, It will open Firefox browser with newly
created profile settings.
Why needs To Set Firefox Profile In Selenium WebDriver
To perform some actions In your selenium webdriver software automation test,
You need special Firefox profile. Some example actions are as bellow where we
need to set Firefox profile. We will learn more about how to perform all those
actions In Selenium webdriver software automation testing tool In my upcoming
posts.

1. To Download files. VIEW EXAMPLE


2. To Set Proxy Settings. VIEW EXAMPLE
3. To Resolve Certificate related errors. VIEW EXAMPLE

If you have any example where we need to set Firefox profile properties then you
can share It with world by commenting bellow.

How To Download Different Files Using


Selenium WebDriver
In my PREVIOUS POST, We have learnt about how to create and use custom
profile of Firefox browser to use It In selenium webdriver software automation
test. Now let me show you how to create Firefox custom profile run time and
set Its properties to download any file using selenium webdriver software
testing tool. Many times you need to download different files from software web
application like MS Excel file, MS Word File, Zip file, PDF file, CSV file, Text
file, ect..

It Is tricky way to download file using selenium webdriver software testing tool.
Manually when you click on link to download file, It will show you dialogue to
save file In your local drive as shown In bellow given Image.
Now selenium webdriver software automation testing tool do not have any feature
to handle this save file dialogue. But yes, Selenium webdriver has one more very
good feature by which you do not need to handle that dialogue and you can
download any file very easily. We can do It using webdriver's Inbuilt class
FirefoxProfile and Its different methods. Before looking at example of
downloading file, Let me describe you some thing about file's MIME types. Yes
you must know MIME type of file which you wants to download using selenium
webdriver software testing tool.

What Is MIME of File


MIME Is full form of Multi-purpose Internet Mail Extensions which Is useful to
Identify file type by browser or server to transfer online.

You need to provide MIME type of file In your selenium webdriver test so that
you must be aware about It. There are many online tools available to know MIME
type of any file. Just google with "MIME checker" to find this kind of tools.

In our example given bellow, I have used MIME types as shown bellow for
different file types In bellow given selenium webdriver test.

1. Text File (.txt) - text/plain


2. PDF File (.pdf) - application/pdf
3. CSV File (.csv) - text/csv
4. MS Excel File (.xlsx) - application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet
5. MS word File (.docx) - application/vnd.openxmlformats-
officedocument.wordprocessingml.document
Example Of downloading different files using selenium webdriver

package Testng_Pack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class downloadingfile {


WebDriver driver;

@BeforeTest
public void StartBrowser() {
//Create object of FirefoxProfile in built class to access Its properties.
FirefoxProfile fprofile = new FirefoxProfile();
//Set Location to store files after downloading.
fprofile.setPreference("browser.download.dir", "D:\\WebDriverdownloads");
fprofile.setPreference("browser.download.folderList", 2);
//Set Preference to not show file download confirmation dialogue using MIME
types Of different file extension types.
fprofile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;"//MIME types Of MS Excel File.
+ "application/pdf;" //MIME types Of PDF File.
+ "application/vnd.openxmlformats-
officedocument.wordprocessingml.document;" //MIME types Of MS doc File.
+ "text/plain;" //MIME types Of text File.
+ "text/csv"); //MIME types Of CSV File.
fprofile.setPreference( "browser.download.manager.showWhenStarting", false
);
fprofile.setPreference( "pdfjs.disabled", true );
//Pass fprofile parameter In webdriver to use preferences to download file.
driver = new FirefoxDriver(fprofile);
}
@Test
public void OpenURL() throws InterruptedException{
driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
//Download Text File
driver.findElement(By.xpath("//a[contains(.,'Download Text
File')]")).click();
Thread.sleep(5000);//To wait till file gets downloaded.
//Download PDF File
driver.findElement(By.xpath("//a[contains(.,'Download PDF
File')]")).click();
Thread.sleep(5000);
//Download CSV File
driver.findElement(By.xpath("//a[contains(.,'Download CSV
File')]")).click();
Thread.sleep(5000);
//Download Excel File
driver.findElement(By.xpath("//a[contains(.,'Download Excel
File')]")).click();
Thread.sleep(5000);
//Download Doc File
driver.findElement(By.xpath("//a[contains(.,'Download Doc
File')]")).click();
Thread.sleep(5000);
}

@AfterTest
public void CloseBrowser() {
driver.quit();
}
}

When you run above example, It will download all 5(Text, pdf, CSV, docx and
xlsx) files one by one and store them In D:\WebDriverdownloads folder
automatically as shown In bellow given example.
InterruptedException Is used with method OpenURL to handle checked
exception of Thread.sleep(5000). View detailed tutorials of exception handling
In selenium WebDriver software test automation on THIS LINK.

This way you can download any file using selenium webdriver like zip file, exe
file, etc.. Just know your file's MIME type and download It as shown In above
example.

How To Handle Ajax Auto Suggest Drop List


In Selenium Webdriver
What Is Ajax Auto Suggest Drop List?
Before learning about how to handle ajax auto suggest drop down
list In selenium webdriver software testing tool, Let me tell you what Is ajax
auto suggest drop down list. If you have visited any software website with
search box and that search box Is showing auto suggest list when you type some
thing Inside It. Simplest example of ajax auto suggest drop list Is Google search
suggestion. When you will type something Inside It, It will show you a list of
suggestions as shown In bellow given Image.
This Is only example for your reference. You will find this kind of ajax drop lists
In many sites.

How to handle ajax drop list In selenium WebDriver


Now supposing you wants to select some value from that auto suggest list or you
wants to store and print all those suggestions then how will you do It?. If you
know, It Is very hard to handle such ajax In selenium IDE software testing tools.
Let we try to print all those suggestions In console.

Here, Xpath pattern Is same for all ajax auto suggest drop list Items. Only
changing Is Value Inside <tr> tag. See bellow xpath of 1st two Items of drop list.

//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[1]/td/div/table/tbody/tr[1]/td
[1]/span
//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr[2]/td/div/table/tbody/tr[1]/td
[1]/span

So we will use for loop(As described In my THIS POST) to feed that changing
values to xpath of drop list different Items. Other one thing we need to consider
Is we don't know how many Items It will show In ajax drop list. Some keywords
show you 4 Items and some other will show you more than 4 Items In drop list.
To handle this dynamic changing list, We will USE TRY CATCH BLOCK to
catch the NoSuchElementException exception if not found next Item In ajax drop
list.
In bellow given example, we have used testng @DataProvider annotation. If you
know, @DataProvider annotation Is useful for data driven software automation
testing. THIS LINKED POST will describe you the usage of @DataProvider
annotation with detailed example and explanation.

Run bellow given example In your eclipse with testng and see how It Is retrieving
values from ajax drop list and print them In console.

package Testng_Pack;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Ajax_Handle {

WebDriver driver = new FirefoxDriver();

@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://www.google.com");
}

@AfterTest
public void tearDown() throws Exception {
driver.quit();
}

//Data provider Is used for supplying 2 different values to Search_Test


method.
@DataProvider(name="search-data")
public Object[][] dataProviderTest(){
return new Object[][]{{"selenium webdriver tutorial"},{"auto s"}};
}

@Test(dataProvider="search-data")
public void Search_Test(String Search){
driver.findElement(By.xpath("//input[@id='gbqfq']")).clear();
driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys(Search);
int i=1;
int j=i+1;
try{
//for loop will run till the NoSuchElementException exception.
for(i=1; i<j;i++)
{
//Value of variable i Is used for creating xpath of drop list's
different elements.
String suggestion =
driver.findElement(By.xpath("//*[@id='gsr']/table/tbody/tr[1]/td[2]/table/tbo
dy/tr["+i+"]/td/div/table/tbody/tr/td[1]/span")).getText();
System.out.println(suggestion);
j++;
}
}catch(Exception e){//Catch block will catch and handle the exception.
System.out.println("***Please search for another word***");
System.out.println();
}
}
}

This way you can also select specific from that suggestion for your searching
purpose. It Is very simple In selenium webdriver software testing tool. You can
use other or more search values In above example. To do It simply modify
@DataProvider annotation method.

Parameterization/Data Driven Testing Of


Selenium Webdriver Test Using Excel
Parameterization or data driven test is must required thing of any
software automation testing tool. If you can not perform data driven testing in
any software automation tool then it is biggest drawback of that tool. Till
now, Selenium webdriver software automation testing tool has not any built in
structure or method to parameterize your test. If you know, we can perform
data driven testing using user extension in selenium IDE software testing tool.
You can view practical example of selenium IDE parameterization test on THIS
ARTICLE POST. To parameterize selenium webdriver test, We need support
of Java Excel API. First of all, we need to configure eclipse. Configuration steps
are as bellow.

Another way of data driven testing In selenium webdriver software testing


tool Is using TestNG @DataProvider Annotation. VIEW STEPS OF DATA
DRIVEN TESTING USING @DataProvider.

Step 1 : Download latest jxl.jar file


Current latest version of jexcelapi is 2_6_12. It may change in future so
download link can also change.

 Click on THIS LINK to go to jexcelapi_2_6_12 page.


 Click on jexcelapi_2_6_12.zip link as shown in bellow image. It will start
downloading zip folder.

 On completion of zip folder download, extract that zip folder. You will
find jxl.jar file inside it.
Step 2 : Add jxl.jar in your project folder as a external jar.
 Right click on your project folder in eclipse and go to Build Path ->
Configure Build path -> Libraries tab -> Click on Add External JARs button and
select jxl.jar.
For detailed description with image on how to add any external jar in your project
folder, You can follow step 2 of THIS POST .

Step 3 : Download data file


I have prepared example data file for parameterization. CLICK HERE to
download data file and save in your D: drive.

Step 4 : Import header files


All Bellow given header files are required for this example. Please include them
in your header file list if not included.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.JavascriptExecutor;

Step 5 : Run bellow given example in your eclipse.


Bellow given example will read data from D:\\MyDataSheet.xls file and then type
that data in First Name and Last Name text box one by one.

Last Name text box will be disabled initially so I have used javascript executor to
enable it. You can view practical example with description for the same on THIS
LINK.

Copy bellow given @Test method part of data driven testing example and
replace it with the @Test method part of example given on THIS PAGE. (Note
: @Test method is marked with pink color in that linked page).

@Test
public void test () throws BiffException, IOException, InterruptedException
{
//Open MyDataSheet.xls file from given location.
FileInputStream fileinput = new FileInputStream("D:\\MyDataSheet.xls");
//Access first data sheet. getSheet(0) describes first sheet.
Workbook wbk = Workbook.getWorkbook(fileinput);
Sheet sheet = wbk.getSheet(0);

//Read data from the first data sheet of xls file and store it in array.
String TestData[][] = new String[sheet.getRows()][sheet.getColumns()];

//To enable Last Name text box.


JavascriptExecutor javascript = (JavascriptExecutor) driver;
String toenable =
"document.getElementsByName('lname')[0].removeAttribute('disabled');";
javascript.executeScript(toenable);

//Type data in first name and last name text box from array.
for(int i=0;i<sheet.getRows();i++)
{
for (int j=0;j<sheet.getColumns();j++)
{
TestData[i][j] = sheet.getCell(j,i).getContents();
if(j%2==0)
{

driver.findElement(By.xpath("//input[@name='fname']")).sendKeys(TestData[i][j
]);
}
else
{

driver.findElement(By.xpath("//input[@name='lname']")).sendKeys(TestData[i][j
]);
}
}
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@name='fname']")).clear();
driver.findElement(By.xpath("//input[@name='lname']")).clear();
}
Thread.sleep(1000);

How to download selenium and install


Selenium Webdriver with Eclipse and Java
Step By Step
Download selenium webdriver and install selenium webdriver is easy. You
need to download selenium jar files. Then configure downloaded selenium jar
files in eclipse. Actually there is nothing to install except JDK. Let me describe
you step by step process of download, installation and configuration of web
driver software and other required components. You can view my post about
"What is selenium webdriver" if you wants to know difference
between WebDriver and selenium RC software tool.

(Note : I am suggesting you to take a tour of Basic selenium commands


tutorials with examples before going ahead for webdriver. It will improve
your basic knowledge and helps you to create webdriver scripts very easily. )

Steps To Setup and configure Selenium Webdriver With Eclipse and Java

(Note : You can View More Articles On WebDriver to learn it step


by step)
Step 1 : Download and install Java in your system
First of all you need to install JDK (Java development kit) software in your
system. So your next question will be "how can i download java" VIEW THIS
ARTICLE to know how to download and install Java(JDK) software.

Step 2 : Download and install Eclipse


Download Eclipse for Java Developers and extract save it in any drive. It is
totally free. You can run 'eclipse.exe' directly so you do not need to install
Eclipse in your system.

Step 3 : Download WebDriver Jar Files.


Selenium webdriver supports many languages and each language has its own
client driver. Here we are configuring selenium 2 software with java so we need
'webdriver Java client driver'. Click here to go on WebDriver Java client driver
download page for webdriver download file. On that page click on 'Download'
link of java client driver as shown in bellow image.
(language-specific client driver's version is changing time to time so it may be
different version when you will visit download page. )

Downloaded 'webDriver Java client driver' will be in zip format. Extract and
save it in your system at path D:\selenium-2.33.0. There will be 'libs' folder, 2
jar files and change log in unzipped folder as shown in bellow figure. We will
use all these files for configuring webdriver in eclipse.

Step 4 : Start Eclipse and configure it with selenium 2 (webdriver)

 Select WorkSpace on eclipse start up


Double click on 'eclipse.exe' to start eclipse software application. First time
when you start eclipse software application, it will ask you to select your
workspace where your work will be stored as shown in bellow image. Create
new folder in D: drive with name 'Webdriverwork' and select it as your
workspace. You can change it later on from 'Switch Workspace' under 'file'
menu of eclipse.

After selecting workspace folder, Eclipse will be open.


 Create new project
Create new java project from File > New > Project > Java Project and give
your project name 'testproject' as shown in bellow given figures. Click on finish
button.
Now your new created project 'testproject' will display in eclipse project
explorer as bellow.
 Create new package
Right click on project name 'testproject' and select New > Package. Give your
package name = 'mytestpack' and click on finish button. It will add new
package with name 'mytestpack' under project name 'testproject'.

 Create New Class


Right click on package 'mytestpack' and select New > Class and set class name
= 'mytestclass' and click on Finish button. It will add new class 'mytestclass'
under package 'mytestpack'.

Now your Eclipse window will looks like bellow.

 Add external jar file to java build path


Now you need to add selenium webdriver's jar files in to java build path.
 Right click on project 'testproject' > Select Properties > Select Java build
path > Navigate to Libraries tab
 Click on add external JARs button > select both .jar files
from D:\selenium-2.33.0.
 Click on add external JARs button > select all .jar files
from D:\selenium-2.33.0\libs
Now your testproject's properties dialogue will looks like bellow.

That's all about configuration of WebDriver software with eclipse. Now you are
ready to write your test in eclipse and run it in WebDriver.

Q #1) What is Automation Testing?


Automation testing or Test Automation is a process of automating the manual process to
test the application/system under test. Automation testing involves use to a separate
testing tool which lets you create test scripts which can be executed repeatedly and doesn’t
require any manual intervention.

Q #2) What are the benefits of Automation Testing?


Benefits of Automation testing are:
1. Supports execution of repeated test cases
2. Aids in testing a large test matrix
3. Enables parallel execution
4. Encourages unattended execution
5. Improves accuracy thereby reducing human generated errors
6. Saves time and money
Q #3) Why should Selenium be selected as a test tool?
Selenium

1. is free and open source


2. have a large user base and helping communities
3. have cross Browser compatibility (Firefox, chrome, Internet Explorer, Safari etc.)
4. have great platform compatibility (Windows, Mac OS, Linux etc.)
5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
6. has fresh and regular repository developments
7. supports distributed testing
Q #4) What is Selenium? What are the different Selenium components?
Selenium is one of the most popular automated testing suites. Selenium is designed in a
way to support and encourage automation testing of functional aspects of web based
applications and a wide range of browsers and platforms. Due to its existence in the open
source community, it has become one of the most accepted tools amongst the testing
professionals.

Selenium is not just a single tool or a utility, rather a package of several testing tools and
for the same reason it is referred to as a Suite. Each of these tools is designed to cater
different testing and test environment requirements.

The suite package constitutes of the following sets of tools:

 Selenium Integrated Development Environment (IDE) – Selenium IDE is a


record and playback tool. It is distributed as a Firefox Plugin.
 Selenium Remote Control (RC) – Selenium RC is a server that allows user to
create test scripts in a desired programming language. It also allows executing test
scripts within the large spectrum of browsers.
 Selenium WebDriver – WebDriver is a different tool altogether that has various
advantages over Selenium RC. WebDriver directly communicates with the web
browser and uses its native compatibility to automate.
 Selenium Grid – Selenium Grid is used to distribute your test execution on multiple
platforms and environments concurrently.
Q #5) What are the testing types that can be supported by Selenium?
Selenium supports the following types of testing:

1. Functional Testing
2. Regression Testing
Q #6) What are the limitations of Selenium?
Following are the limitations of Selenium:

 Selenium supports testing of only web based applications


 Mobile applications cannot be tested using Selenium
 Captcha and Bar code readers cannot be tested using Selenium
 Reports can only be generated using third party tools like TestNG or Junit.
 As Selenium is a free tool, thus there is no ready vendor support though the user can
find numerous helping communities.
 User is expected to possess prior programming language knowledge.
Q #7) What is the difference between Selenium IDE, Selenium RC and WebDriver?
Feature Selenium IDE Selenium RC WebDriver

Browser Selenium IDE Selenium RC WebDriver


Compatibility comes as a supports a varied supports a varied
Firefox plugin, range of versions range of versions
thus it supports of Mozilla of Mozilla
only Firefox Firefox, Google Firefox, Google
Chrome, Internet Chrome, Internet
Explorer and Explorer and
Opera Opera.
Also supports
HtmlUnitDriver
which is a GUI
less or headless
browser.

Record and Selenium IDE Selenium RC WebDriver


Playback supports record doesn't supports doesn't support
and playback record and record and
feature playback feature playback feature

Server Selenium IDE Selenium RC WebDriver


Requirement doesn't require requires server to doesn't require
any server to be be started before any server to be
started before executing the started before
executing the test scripts executing the
test scripts test scripts

Architecture Selenium IDE is a Selenium RC is a WebDriver uses


Javascript based JavaScript based the browser's
framework Framework native
compatibility to
automation
Feature Selenium IDE Selenium RC WebDriver

Object Oriented Selenium IDE is Selenium RC is WebDriver is a


not an object semi object purely object
oriented tool oriented tool oriented tool

Dynamic Finders Selenium IDE Selenium RC WebDriver


(for locating web doesn't support doesn't support supports
elements on a dynamic finders dynamic finders dynamic finders
webpage)

Handling Alerts, Selenium IDE Selenium RC WebDriver offers


Navigations, doesn't explicitly doesn't explicitly a wide range of
Dropdowns provides aids to provides aids to utilities and
handle alerts, handle alerts, classes that helps
navigations, navigations, in handling
dropdowns dropdowns alerts,
navigations, and
dropdowns
efficiently and
effectively.

WAP Selenium IDE Selenium RC WebDriver is


(iPhone/Android) doesn't support doesn't support designed in a
Testing testing of testing of way to efficiently
iPhone/Andriod iPhone/Andriod support testing
applications applications of
iPhone/Android
applications. The
tool comes with
a large range of
drivers for WAP
based testing.
For example,
AndroidDriver,
iPhoneDriver
Feature Selenium IDE Selenium RC WebDriver

Listener Support Selenium IDE Selenium RC WebDriver


doesn't support doesn't support supports the
listeners listeners implementation
of Listeners

Speed Selenium IDE is Selenium RC is WebDriver


fast as it is slower than communicates
plugged in with WebDriver as it directly with the
the web- doesn't web browsers.
browser that communicates Thus making it
launches the directly with the much faster.
test. Thus, the browser; rather it
IDE and browser sends selenese
communicates commands over
directly to Selenium Core
which in turn
communicates
with the browser.

Q #8) When should I use Selenium IDE?


Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its
record and playback feature makes it exceptionally easy to learn with minimal
acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

Q #9) What is Selenese?


Selenese is the language which is used to write test scripts in Selenium IDE.

Q #10) What are the different types of locators in Selenium?


Locator can be termed as an address that identifies a web element uniquely within the
webpage. Thus, to identify web elements accurately and precisely we have different types of
locators in Selenium:
 ID
 ClassName
 Name
 TagName
 LinkText
 PartialLinkText
 Xpath
 CSS Selector
 DOM
Q #11) What is difference between assert and verify commands?
Assert: Assert command checks whether the given condition is true or false. Let’s say we
assert whether the given element is present on the web page or not. If the condition is true
then the program control will execute the next test step but if the condition is false, the
execution would stop and no further test would be executed.
Verify: Verify command also checks whether the given condition is true or false.
Irrespective of the condition being true or false, the program execution doesn’t halts i.e.
any failure during verification would not stop the execution and all the test steps would be
executed.
Q #12) What is an Xpath?
Xpath is used to locate a web element based on its XML path. XML stands for Extensible
Markup Language and is used to store, organize and transport arbitrary data. It stores data
in a key-value pair which is very much similar to HTML tags. Both being markup languages
and since they fall under the same umbrella, Xpath can be used to locate HTML elements.
The fundamental behind locating elements using Xpath is the traversing between various
elements across the entire page and thus enabling a user to find an element with the
reference of another element.

Q #13) What is the difference between “/” and “//” in Xpath?


Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath
would be created to start selection from the document node/start node.
Double Slash “//” – Double slash is used to create Xpath with relative path i.e. the xpath
would be created to start selection from anywhere within the document.
Q #14) What is Same origin policy and how it can be handled?
The problem of same origin policy disallows to access the DOM of a document from an origin
that is different from the origin we are trying to access the document.

Origin is a sequential combination of scheme, host and port of the URL. For example, for a
URL http:// http://www.softwaretestinghelp.com/resources/, the origin is a combination of
http, softwaretestinghelp.com, 80 correspondingly.

Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin
that is different from where it was launched. For Example, if I have launched the JavaScript
Program from “http://www.softwaretestinghelp.com”, then I would be able to access the
pages within the same domain such as “http://www.softwaretestinghelp.com/resources” or
“http://www.softwaretestinghelp.com/istqb-free-updates/”. The other domains like
google.com, seleniumhq.org would no more be accessible.

So, In order to handle same origin policy, Selenium Remote Control was introduced.
Q #15) When should I use Selenium Grid?
Selenium Grid can be used to execute same or different test scripts on multiple platforms
and browsers concurrently so as to achieve distributed test execution, testing under
different environments and saving execution time remarkably.
Q #16) What do we mean by Selenium 1 and Selenium 2?
Selenium RC and WebDriver, in a combination are popularly known as Selenium 2. Selenium
RC alone is also referred as Selenium 1.
Q #17) Which is the latest Selenium tool?
WebDriver

Q #18) How do I launch the browser using WebDriver?


The following syntax can be used to launch Browser:
WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();
Q #19) What are the different types of Drivers available in WebDriver?
The different drivers available in WebDriver are:

 FirefoxDriver
 InternetExplorerDriver
 ChromeDriver
 SafariDriver
 OperaDriver
 AndroidDriver
 IPhoneDriver
 HtmlUnitDriver
Q #20) What are the different types of waits available in WebDriver?
There are two types of waits available in WebDriver:
1. Implicit Wait
2. Explicit Wait
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds)
between each consecutive test step/command across the entire test script. Thus,
subsequent test step would only execute when the 30 seconds have elapsed after executing
the previous test step/command.
Explicit Wait: Explicit waits are used to halt the execution till the time a particular
condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit waits are
applied for a particular instance only.
Q #21) How to type in a textbox using Selenium?
User can use sendKeys(“String to be entered”) to enter the string in the textbox.

Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);
Q #22) How can you find if an element in displayed on the screen?
WebDriver facilitates the user with the following methods to check the visibility of the web
elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons,
labels etc.

1. isDisplayed()
2. isSelected()
3. isEnabled()
Syntax:
isDisplayed():
boolean buttonPresence =
driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected =
driver.findElement(By.id(“gbqfba”)).isDisplayed();
isEnabled():
boolean searchIconEnabled =
driver.findElement(By.id(“gbqfb”)).isEnabled();
Q #23) How can we get a text of a web element?
Get command is used to retrieve the inner text of the specified web element. The command
doesn’t require any parameter but returns a string value. It is also one of the extensively
used commands for verification of messages, labels, errors etc displayed on the web pages.

Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();
Q #24) How to select value in a dropdown?
Value in the drop down can be selected using WebDriver’s Select class.

Syntax:
selectByValue:
Select selectByValue
= newSelect(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:
Select selectByVisibleText = new Select
(driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex:
Select selectByIndex
= newSelect(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);
Q #25) What are the different types of navigation commands?
Following are the navigation commands:
navigate().back() – The above command requires no parameters and takes back the user
to the previous webpage in the web browser’s history.
Sample code:
driver.navigate().back();
navigate().forward() – This command lets the user to navigate to the next web page with
reference to the browser’s history.
Sample code:
driver.navigate().forward();
navigate().refresh() – This command lets the user to refresh the current web page there
by reloading all the web elements.
Sample code:
driver.navigate().refresh();
navigate().to() – This command lets the user to launch a new web browser window and
navigate to the specified URL.
Sample code:
driver.navigate().to(“https://google.com”);
Q #26) How to click on a hyper link using linkText?
driver.findElement(By.linkText(“Google”)).click();
The command finds the element using link text and then click on that element and thus the
user would be re-directed to the corresponding page.
The above mentioned link can also be accessed by using the following command.

------------
driver.findElement(By.partialLinkText(“Goo”)).click();
The above command find the element based on the substring of the link provided in the
parenthesis and thus partialLinkText() finds the web element with the specified substring
and then clicks on it.

Q #27) How to handle frame in WebDriver?


An inline frame acronym as iframe is used to insert another document with in the current
HTML document or simply a web page into a web page by enabling nesting.

Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
Locating iframe using index
frame(index)
driver.switchTo().frame(0);
frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
Q #28) When do we use findElement() and findElements()?
findElement(): findElement() is used to find the first element in the current web page
matching to the specified locator value. Take a note that only first matching element would
be fetched.
Syntax:
WebElement element
=driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web page
matching to the specified locator value. Take a note that all the matching elements would
be fetched and stored in the list of WebElements.
Syntax:
List <WebElement> elementList
=driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
Q #29) How to find more than one web element in the list?
At times, we may come across elements of same type like multiple hyperlinks, images etc
arranged in an ordered or unordered list. Thus, it makes absolute sense to deal with such
elements by a single piece of code and this can be done using WebElement List.

Sample Code
1 // Storing the list

List <WebElement> elementList =


2
driver.findElements(By.xpath("//div[@id='example']//ul//li"));
3 // Fetching the size of the list

4 int listSize = elementList.size();

5 for (int i=0; i<listSize; i++)

6{

7 // Clicking on each service provider link

8 serviceProviderLinks.get(i).click();

// Navigating back to the previous page that stores link to service


9
providers

10 driver.navigate().back();

11 }

Q #30) What is the difference between driver.close() and driver.quit command?


close(): WebDriver’s close() method closes the web browser window that the user is
currently working on or we can also say the window that is being currently accessed by the
WebDriver. The command neither requires any parameter nor does is return any value.
quit(): Unlike close() method, quit() method closes down all the windows that the program
has opened. Same as close() method, the command neither requires any parameter nor
does is return any value.
Q #31) Can Selenium handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing.
Therefore, windows pop up cannot be handled using Selenium.

Q #32) How can we handle web based pop up?


WebDriver offers the users with a very efficient way to handle these pop ups using Alert
interface. There are the four methods that we would be using along with the Alert interface.
 void dismiss() – The accept() method clicks on the “Cancel” button as soon as the
pop up window appears.
 void accept() – The accept() method clicks on the “Ok” button as soon as the pop up
window appears.
 String getText() – The getText() method returns the text displayed on the alert box.
 void sendKeys(String stringToSend) – The sendKeys() method enters the specified
string pattern into the alert box.
Syntax:
// accepting javascript alert
Alert alert = driver.switchTo().alert();
alert.accept();
Q #33) How can we handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing, that
means, it doesn’t support testing of windows based applications. However Selenium alone
can’t help the situation but along with some third party intervention, this problem can be
overcome. There are several third party tools available for handling window based pop ups
along with the selenium like AutoIT, Robot class etc.
Q #34) How to assert title of the web page?
//verify the title of the web page
assertTrue(“The title of the window is
incorrect.”,driver.getTitle().equals(“Title of the page”));
Q #35) How to mouse hover on a web element using WebDriver?
WebDriver offers a wide range of interaction utilities that the user can exploit to automate
mouse and keyboard events. Action Interface is one such utility which simulates the single
user interactions.

Thus, In the following scenario, we have used Action Interface to mouse hover on a drop
down which then opens a list of options.

Sample Code:
1 // Instantiating Action Interface

2 Actions actions=new Actions(driver);

3 // howering on the dropdown

actions.moveToElement(driver.findElement(By.id("id of the
4
dropdown"))).perform();

5 // Clicking on one of the items in the list options

6 WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));

7 subLinkOption.click();

Q #36) How to retrieve css properties of an element?


The values of the css properties can be retrieved using a get() method:

Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);
Q #37) How to capture screenshot in WebDriver?
1 import org.junit.After;

2 import org.junit.Before;

3 import org.junit.Test;

4 import java.io.File;

5 import java.io.IOException;

6 import org.apache.commons.io.FileUtils;

7 import org.openqa.selenium.OutputType;
8 import org.openqa.selenium.TakesScreenshot;

9 import org.openqa.selenium.WebDriver;

10 import org.openqa.selenium.firefox.FirefoxDriver;

11

12 public class CaptureScreenshot {

13 WebDriver driver;

14 @Before

15 public void setUp() throws Exception {

16 driver = new FirefoxDriver();

17 driver.get("https://google.com");

18 }

19 @After

20 public void tearDown() throws Exception {

21 driver.quit();

22 }

23

24 @Test

25 public void test() throws IOException {

26 // Code to capture the screenshot

27 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

28 // Code to copy the screenshot in the desired location

2 FileUtils.copyFile(scrFile, newFile("C:\\CaptureScreenshot\\google.jpg"));
9

3
}
0

31 }

Q #38) What is Junit?


Junit is a unit testing framework introduced by Apache. Junit is based on Java.
Q #39) What are Junit annotations?
Following are the Junit Annotations:

 @Test: Annotation lets the system know that the method annotated as @Test is a
test method. There can be multiple test methods in a single test script.
 @Before: Method annotated as @Before lets the system know that this method shall
be executed every time before each of the test method.
 @After: Method annotated as @After lets the system know that this method shall be
executed every time after each of the test method.
 @BeforeClass: Method annotated as @BeforeClass lets the system know that this
method shall be executed once before any of the test method.
 @AfterClass: Method annotated as @AfterClass lets the system know that this
method shall be executed once after any of the test method.
 @Ignore: Method annotated as @Ignore lets the system know that this method
shall not be executed.
Q #40) What is TestNG and how is it better than Junit?
TestNG is an advance framework designed in a way to leverage the benefits by both the
developers and testers. With the commencement of the frameworks, JUnit gained an
enormous popularity across the Java applications, Java developers and Java testers with
remarkably increasing the code quality. Despite being easy to use and straightforward, JUnit
has its own limitations which give rise to the need of bringing TestNG into the picture.
TestNG is an open source framework which is distributed under the Apache software License
and is readily available for download.
TestNG with WebDriver provides an efficient and effective test result format that can in turn
be shared with the stake holders to have a glimpse on the product’s/application’s health
thereby eliminating the drawback of WebDriver’s incapability to generate test reports.
TestNG has an inbuilt exception handling mechanism which lets the program to run without
terminating unexpectedly.
There are various advantages that make TestNG superior to JUnit. Some of them are:

 Added advance and easy annotations


 Execution patterns can set
 Concurrent execution of test scripts
 Test case dependencies can be set
Q #41) How to set test case priority in TestNG?
Setting Priority in TestNG
Code Snippet
1 package TestNG;

2 import org.testng.annotations.*;

3 public class SettingPriority {

4 @Test(priority=0)

5 public void method1() {

6 }

7 @Test(priority=1)
8 public void method2() {

9 }

10 @Test(priority=2)

11 public void method3() {

12 }

13 }

Test Execution Sequence:


1. Method1
2. Method2
3. Method3
Q #42) What is a framework?
Framework is a constructive blend of various guidelines, coding standards, concepts,
processes, practices, project hierarchies, modularity, reporting mechanism, test data
injections etc. to pillar automation testing.

Q #43) What are the advantages of Automation framework?


Advantage of Test Automation framework
 Reusability of code
 Maximum coverage
 Recovery scenario
 Low cost maintenance
 Minimal manual intervention
 Easy Reporting
Q #44) What are the different types of frameworks?
Below are the different types of frameworks:
1. Module Based Testing Framework: The framework divides the entire “Application
Under Test” into number of logical and isolated modules. For each module, we create
a separate and independent test script. Thus, when these test scripts taken together
builds a larger test script representing more than one module.
2. Library Architecture Testing Framework: The basic fundamental behind the
framework is to determine the common steps and group them into functions under a
library and call those functions in the test scripts whenever required.
3. Data Driven Testing Framework: Data Driven Testing Framework helps the user
segregate the test script logic and the test data from each other. It lets the user
store the test data into an external database. The data is conventionally stored in
“Key-Value” pairs. Thus, the key can be used to access and populate the data within
the test scripts.
4. Keyword Driven Testing Framework: The Keyword driven testing framework is
an extension to Data driven Testing Framework in a sense that it not only segregates
the test data from the scripts, it also keeps the certain set of code belonging to the
test script into an external data file.
5. Hybrid Testing Framework: Hybrid Testing Framework is a combination of more
than one above mentioned frameworks. The best thing about such a setup is that it
leverages the benefits of all kinds of associated frameworks.
6. Behavior Driven Development Framework: Behavior Driven Development
framework allows automation of functional validations in easily readable and
understandable format to Business Analysts, Developers, Testers, etc.
Q #45) How can I read test data from excels?
Test data can efficiently be read from excel using JXL or POI API.See detailed tutorial here.
Q #46) What is the difference between POI and jxl jar?
# JXL jar POI jar

1 JXL supports “.xls” format i.e. POI jar supports all of


binary based format. JXL doesn’t these formats
support Excel 2007 and “.xlsx”
format i.e. XML based format

2 JXL API was last updated in the POI is regularly updated


year 2009 and released

3 The JXL documentation is not as POI has a well prepared


comprehensive as that of POI and highly
comprehensive
documentation

4 JXL API doesn’t support rich text POI API supports rich
formatting text formatting

5 JXL API is faster than POI API POI API is slower than
JXL API

Q #47) What is the difference between Selenium and QTP?


Quick Test
Feature Selenium
Professional (QTP)

Browser Selenium supports QTP supports Internet


Compatibility almost all the popular Explorer, Firefox and
browsers like Firefox, Chrome. QTP only
Chrome, Safari, Internet supports Windows
Explorer, Opera etc Operating System

Distribution Selenium is distributed QTP is distributed as a


as an open source tool licensed tool and is
and is freely available commercialized
Quick Test
Feature Selenium
Professional (QTP)

Application Selenium supports QTP supports testing of


under Test testing of only web both the web based
based applications application and
windows based
application

Object Object Repository needs QTP automatically


Repository to be created as a creates and maintains
separate entity Object Repository

Language Selenium supports QTP supports only VB


Support multiple programming Script
languages like Java, C#,
Ruby, Python, Perl etc

Vendor As Selenium is a free Users can easily get


Support tool, user would not get the vendor’s support in
the vendor’s support in case of any issue
troubleshooting issues

Q #48) Can WebDriver test Mobile applications?


WebDriver cannot test Mobile applications. WebDriver is a web based testing tool, therefore
applications on the mobile browsers can be tested.

Q #49) Can captcha be automated?


No, captcha and bar code reader cannot be automated.

Q #50) What is Object Repository? How can we create Object Repository in


Selenium?
Object Repository is a term used to refer to the collection of web elements belonging to
Application Under Test (AUT) along with their locator values. Thus, whenever the element is
required within the script, the locator value can be populated from the Object Repository.
Object Repository is used to store locators in a centralized location instead of hard coding
them within the scripts.

In Selenium, objects can be stored in an excel sheet which can be populated inside the
script whenever required.

You might also like