@@selenium QA

You might also like

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

Selenium Interview Questions and Answers

1. Explain Selenium Architecture?


Ans -

1. Language binding: To support multiple languages, selenium people has developed


language bindings. If you want to use the browser driver in Java, use the Java bindings
for Selenium Webdriver. If you want to use the browser driver in C#, Ruby or Python,
use the binding for that language.
using these languages we can make a framework. Using these language level bindings
we can implement selenium WebDriver code. Once we make the framework using
these programming languages, it will help to interact with the selenium WebDriver and
then can work on different browsers.
2. Selenium Webdriver: It is an API which makes possible to communication between
programming languages and browsers. It follows object oriented concepts. It has
multiple classes and interfaces.
Now the bindings whatever we take and create a framework, communicates with
WebDriver API. The WebDriver API interprets the command taken from Bindings
and transfers it to the respective Driver. In short you can say that the WebDriver API
has a common library which sends commands to respective Drivers.

3. Browser drivers: A browser drivers helps in communication with browser without


revealing the internal logic of browser’s functionality. The browser driver is the same
regardless of the language used for automation.
Now the Driver interprets the commands send by the WebDriver API on the respective
browser. And once the command is executed the result is sent back through the API to
you where you can see the result on your system where you have written the code.

2. Difference between selenium-IDE ,selenium RC,selenium WebDriver?

Selenium IDE Selenium RC Selenium WebDriver

It supports with all It supports with all


It only works in Mozilla
browsers like Firefox, IE, browsers like Firefox, IE,
browser.
Chrome, Safari, Opera etc. Chrome, Safari, Opera etc.

It supports Record and It doesn’t supports Record It doesn’t supports Record


playback and playback and playback

Doesn’t required to start Required to start server Doesn’t required to start


server before executing the before executing the test server before executing the
test script. script. test script.

It is standalone java It actual core API which


It is a GUI Plug-in program which allow you to has binding in a range of
run Html test suites. languages.
Core engine is Javascript Core engine is Javascript Interacts natively with
based based browser application

Very simple to use as it is As compared to RC, it is bit


It is easy and small API
record & playback. complex and large API.

API’s are less Object API’s are entirely Object


It is not object oriented
oriented oriented

It doesn’t supports of It doesn’t supports of It supports of moving


moving mouse cursors. moving mouse cursors. mouse cursors.

No need to append full


Need to append full xpath Need to append full xpath
xpath with ‘xpath=\\’
with ‘xpath=\\’ syntax with ‘xpath=\\’ syntax
syntax

It does not supports It does not supports It supports the


listeners listeners implementation of listeners

It does not support to test It does not support to test It support to test
iphone/Android iphone/Android iphone/Android
applications applications applications

5. What is API? Where it is being used?


An application programming interface (API) is a particular set of rules (‘code’) and
specifications that software programs can follow to communicate with each other. It serves
as an interface between different software programs and facilitates their interaction, similar
to the way the user interface(UI) facilitates interaction between humans and computers.
Selenium Webdriver is also a well-designed object oriented API which helps in
communication between languages and browsers.
1. allows your product or service to talk to other products or services.
2. API allows you to open up data and functionality to other developers and to other
businesse
3. way in which agencies and companies exchange data and services, both internally
and externally.

6. Difference between close() and quit()


close() –
It is WebDriver command.It closes the browser window which is in focus.
If there are more than one browser window opened by the selenium automation,then the
close() command will only close the browser window which is having focus at that time. It
won’t close the remaining browser windows.

Quit()-

It is WebDriver command.It is generally used to shut down the webdrivers instance.


Hence it closes all the browser windows that are opened by the selenium automation.

7.How to maximize & minimize the browser?

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

Minimize – driver.manage().window().minimize();

8.What is webDriver? Interface or class.


WebDriver is a abstract class.
WebDriver is an Interface,
It is a automation framework. That allows you to execute your tests against different
browsers. WebDriver also enables you to use a programming language in creating your test
scripts. It controls browser from the OS level.
9.What is Super interface for WebDriver?

Ans – SearchContext.

10.What is WebElement & explain all methods available in webElement?

Ans-It is a interface.

WebElement represents an HTML element.

All operations to do with intraction with a page will be performed through webElement
interface.

Methods of WebElement-

1) Clear Command

clear( ) : void – If this element is a text entry element, this will clear the value. This method
accepts nothing as a parameter and returns nothing.

Command – element.clear();

This method has no effect on other elements. Text entry elements are INPUT and
TEXTAREA elements.

2) SendKeys Command

sendKeys(CharSequence… keysToSend ) : void – This simulate typing into an element,


which may set its value. This method accepts CharSequence as a parameter and returns
nothing.
Command – element.sendKeys(“text”);

This method works fine with text entry elements like INPUT and TEXTAREA elements.

3) Click Command

click( ) : void – This simulates the clicking of any element. Accepts nothing as a parameter
and returns nothing.

Command – element.click();

Clicking is perhaps the most common way of interacting with web elements like text
elements, links, radio boxes and many more.

4) IsDisplayed Command

isDisplayed( ) : boolean – This method determines if an element is currently being displayed


or not. This accepts nothing as a parameter but returns boolean value(true/false).

Command – element.isDisplayed();

5) IsEnabled Command

isEnabled( ) : boolean – This determines if the element currently is Enabled or not? This
accepts nothing as a parameter but returns boolean value(true/false).

Command – element.isEnabled();

This will generally return true for everything but I am sure you must have noticed many
disabled input elements in the web pages.
6) IsSelected Command

isSelected( ) : boolean – Determine whether or not this element is selected or not. This
accepts nothing as a parameter but returns boolean value(true/false).

Command – element.isSelected();

This operation only applies to input elements such as Checkboxes, Select Options and Radio
Buttons. This returns True if the element is currently selected or checked, false otherwise.

7) Submit Command

submit( ) : void– This method works well/better than the click() if the current element is a
form, or an element within a form. This accepts nothing as a parameter and returns nothing.

Command – element.submit();

If this causes the current page to change, then this method will wait until the new page is
loaded.

8) getTagName Command

getTagName( ) : String– This method gets the tag name of this element. This accepts
nothing as a parameter and returns a String value.

Command – element.getTagName();

This does not return the value of the name attribute but return the tag for e.g. “input“ for the
element <input name="foo"/>.
9) getCssValue Command

getCssvalue( ) : String– This method Fetch CSS property value of the give element. This
accepts nothing as a parameter and returns a String value.

Command – element.getCssValue();

Color values should be returned as rgba strings, so, for example if the “background-color”
property is set as “green” in the HTML source, the returned value will be “rgba(0, 255, 0,
1)”.

10) getAttribute Command

getAttribute(String Name) : String– This method gets the value of the given attribute of the
element. This accepts the String as a parameter and returns a String value.

Command – element.getAttribute();

Attributes are Ids, Name, Class extra and using this method you can get the value of the
attributes of any given element.

11) getSize Command

getSize( ) : Dimension – This method fetch the width and height of the rendered
element. This accepts nothing as a parameter but returns the Dimension object.

Command – element.getSize();

This returns the size of the element on the page


12) getLocation Command

getLocation( ) : Point – This method locate the location of the element on the page. This
accepts nothing as a parameter but returns the Point object.

Command – element.getLocation();

This returns the Point object, from which we can get X and Y coordinates of specific
element.

11) How many locator is avilable in webdriver & which locator is prefered?
Ans : ID Name,LinkText,Partial link Text,Tag Name,css class,css selector,xpath.Finding
elements by ID is usually going to be the fastest option, because at its root, it eventually
calls down to document.getElementById(), which is optimized by many browsers.

12) How to check the object is avilable in Gui?


Ans: WebElement element = driver.findElement(By.id("UserName"));
boolean status = element.isDisplayed();

13)How to check the text from the ui?


Ans: if(driver.getpagesource().contains(“parshu”));
Sysout (“present”)
Else
Sysout(“not present”)
14)How to capture color,Height width font size of element? Getsize,
Ans: Use the Css value of webelement

15)How to get the location of the webelement?


Ans: WebElement element = driver.findElement(By.id("SubmitButton"));
Point point = element.getLocation();
System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y);

16) How to check whether object is selected or not?


Ans: webelement element=driver.findelement(By.id(“sex-male”));
Boolean status=element.isselected();

17)How to check whether object is enabled in gui?


Ans: webelement element=driver.findelement(By.id(“sex-male”));
Boolean status=element.isEnabled()
18)How to delete all cookies
Test
public void deleteAllCookiesExample()
{
driver= new FirefoxDriver();
String URL="http://www.flipcart.com";
driver.navigate().to(URL);
driver.manage().deleteAllCookies();
}

19) Do we use any constructor in webdriver?


Ans : No we didn’t use.
If u are asking about firefox driver then at the time of GRID Yes we did use to create node.

20)How to compare to image


Ans Sikuli, imagemagic are the tools to compare images.

Ex:
Screen s=new Screen();

s.find("pause.png"); //identify pause button

s.click("pause.png"); //click pause button

System.out.println("pause button clicked");

Q.21. How to get webelement height and width?


We use getSize() method to get height and width of element.
getSize() :
-It will returns the "Dimension" object.
-If you want to get the width and Height of the specific element on the webpage then use
"getsize()" method.
Sample code to get the width and height :
WebDriver driver = new FirefoxDriver();
driver.get("https://google.com");
Dimension dimesions=driver.findElement(By.id("gbqfsa")).getSize();
System.out.println("Width : "+dimesions.width);
System.out.println("Height : "+dimesions.height);

Example-
@Test
Public void getSize() throws Exception {
//Locate element for which you wants to get height and width.
WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));

//Get width of element.


intImageWidth = Image.getSize().getWidth();
System.out.println("Image width Is "+ImageWidth+" pixels");

//Get height of element.


int ImageHeight = Image.getSize().getHeight();
System.out.println("Image height Is "+ImageHeight+" pixels");
}
}
Q.22. What is Synchonization?
Synchronization in Java:
Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Synchronization in Selenium Webdriver:
Synchronization is a mechanism which involves two or more components working
parallel with each other. Usually, in test automation, there will be two components
such as application under test and the test automation tool. Both of them will have
specified speeds and the test scripts should be written in a way such that both
these components will work with same speed. This will help to avoid “Element Not
Found” error which otherwise will consume more time to clear off. Here the
synchronization will come for the help.
Generally, there are two different categories of synchronization in test automation
and here is a brief about them.

Unconditional Synchronization
In this case, only the timeout value to be specified. The tool will wait till certain
time before proceeding.
Examples: Wait(), Thread.Sleep()
The main advantage of this method is that it will come for help when we interact
with a third party system such as an interface. Here, it is not possible to write
condition or check for a condition. In such cases, the application can be made to
wait for a specific period using this type of synchronization. The major disadvantage
is that at some times, the tool will be made to wait unnecessarily even when the
application is ready.

Conditional Synchronization
In this case, a condition also will be specified along with the timeout value. The tool
will wait to check the condition and will come out if nothing happens. However, it is
important to set a timeout value also in conditional synchronization so that the tool
will proceed even if the condition is not met.
There three different types of conditional statements in selenium webdriver and
they are an implicit wait and explicit wait and fluent wait.
Implicit Wait
This can be used while trying to find out an element or elements and when they are
not readily available. The implicit wait will tell the webdriver to poll the DOM for a
certain period of time. However, this will not work for all commands but only for
“Find Element” and “Find Elements” statements.
Syntax
driver.manage.TimeOuts.implicitwait(6,Timeunit.SECONDS);
Example for Implicit Wait
WebDriver driver = new FirefoxDiriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(“http://www.google.com”);
Explicit Wait
Here, in this case, a wait statement for certain conditions will be defined which
should be satisfied within the specified timeout period. The code will be executed if
the element is found within the specified time.
Example for Explicit Wait
/*Explicit wait for state dropdown field*/
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“statedropdown”)))
;
Fluent Wait
This is used to define maximum amount of time to wait for a condition and also to
increase the frequency with which the conditions are checked. Using this type
certain types of exceptions such as “NoSuchElementExceptions” can be ignored
too.
Syntax
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
//Wait for the condition
.withTimeout(30, TimeUnit.SECONDS)
// which to check for the condition with interval of 5 seconds.
.pollingEvery(5, TimeUnit.SECONDS)
//Which will ignore the NoSuchElementException
.ignoring(NoSuchElementException.class);
Q.23. How to handle synchronization wait available in webdriver?
We need Expected conditions in Explicit wait to handle synchronization wait.
Explicit Wait-
Here, in this case, a wait statement for certain conditions will be defined which
should be satisfied within the specified timeout period. The code will be executed if
the element is found within the specified time.
Example for Explicit Wait
/*Explicit wait for state dropdown field*/
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“statedropdown”)))
;
Expected conditions methods-
1.isElementPresent:
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
2.isElementClickable-
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
3.isElementVisible-
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
4.isElementInVisible-
Syntax-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));
5.isElementEnabled-
WebElement element = driver.findElement(By.id(""));
element.isEnabled();
6.isElementDisplayed-
WebElement element = driver.findElement(By.id(""));
element.isDisplayed();
7.Wait for invisibility of element-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by));
8.Wait for invisibility of element with Text-
WebDriverWaitwait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by, strText));
Q.24. Which wait statement will be used to wait till page load?
1.Explicit Wait – Webdriver wait with expected conditions Statement is used to
wait till page load.
2. Fluent wait is also used to wait till page load.
Q.25. How to handle dynamic object?

Dynamic object is handled using dynamic xpath . Below are few common techniques used
to handle dynamic objects.

• Using Single Slash-


This mechanism is also known as finding elements using Absolute XPath.
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/parent node.
Syntax
html/body/div[1]/div[2]/div[2]/div[1]/form/div[1]/div/div[1]/div/div/input[1]
• Using Double Slash-
This mechanism is also known as finding elements using Relative XPath.
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. – Search in a whole
page (DOM) for the preceding string

Syntax
//form/div[1]/div/div[1]/div/div/input[1]
• Using Single Attribute-You could write the syntax in two ways as mentioned below.
Including or excluding HTML Tag. If you want to exclude HTML Tag then you need
to use *
• Syntax
//<HTML tag>[@attribute_name='attribute_value']
OR
//*[@attribute_name='attribute_value']

Note: ‘*‘ after double slash is to match any tag with the desired text
• Using Multiple Attribute-
Syntax
//<HTMLtag>[@attribute_name1='attribute_value1'][@attribute_name2='attribute_valu
e2]

OR
//*[@attribute_name1='attribute_value1'][@attribute_name2='attribute_value2]
• Using AND
Syntax
//<HTML tag>[@attribute_name1='attribute_value1' and
@attribute_name2='attribute_value2]
OR
//<HTML tag>[@attribute_name1='attribute_value1' and
@attribute_name2='attribute_value2]
• Using OR-
Syntax
//<HTML tag>[@attribute_name1='attribute_value1' or
@attribute_name2='attribute_value2]
OR
//*[@attribute_name1='attribute_value1' or @attribute_name2='attribute_value2]
• Using contains()
It is used to identify an element, when we are familiar with some part of the
attributes value of an element.
Syntax
//<HTML tag>[contains(@attribute_name,'attribute_value')]
OR
//*[contains(@attribute_name,'attribute_value')]
• Using starts_with()
starts-with(): It is used to identify an element, when we are familiar with the
attributes value (starting with the specified text) of an element.
• Syntax
//<HTML tag>[starts-with(@attribute_name,'attribute_value')]
OR
//*[starts-with(@attribute_name,'attribute_value')]
• Using text()
text(): This mechanism is used to locate an element based on the text available on
a webpage

As per the above image, we could identify the elements text based on the below
xpath.
• Syntax
//*[text()='New look for sign-in coming soon']
• Using last()
last(): Selects the last element (of mentioned type) out of all input element present
To identify the element (last text field ) “Your current email address”, we could use
the below xpath.
- findElement(By.xpath("(//input[@type='text'])[last()]"))
[last()-1] – Selects the last but one element (of mentioned type) out of all input element
present
findElement(By.xpath("(//input[@type='text'])[last()-1]"))
• Using position()
position(): Selects the element out of all input element present depending on the
position number provided
In below given xpath, [@type=’text’] will locate text field and
function [position()=2] will locate text filed which is located on 2nd position from
the top.
findElement(By.xpath("(//input[@type='text'])[position()=2]"))
or
findElement(By.xpath("(//input[@type='text'])[2]"))

• Using index()
By providing the index position in the square brackets, we could move to the nth
element. Based on the below xpath, we could identify the Last Name field.
findElement(By.xpath("//label[2]"))
• Using following xpath axes
following: By using this we could select everything on the web page after the
closing tag of the current node
xpath of the FirstName field is as follows
//*[@id='FirstName']
To identify the input field of type text after the FirstName field, we need to use the
below xpath.
//*[@id='FirstName']/following::input[@type='text']
Here I used, following xpath axes and two colons and then specified the required tag (i.e.,
input)
To identify just the input field after the FirstName field, we need to use the below xpath.
//*[@id='FirstName']/following::input
• Using preceding xpath axes
preceding: Selects all nodes that appear before the current node in the document,
except ancestors, attribute nodes and namespace nodes
xpath of the LastName field is as follows
//*[@id='LastName']
To identify the input field of type text before the LastName field, we need to use the
below xpath.
//*[@id='LastName']//preceding::input[@type='text']"

Here I used, preceding xpath axes and two colons and then specified the required tag (i.e.,
input).
If you are not regular reader of my blog then I highly recommend you to signup for the
free email newsletter using the below link.
Q.26. Difference between thread wait, implicit wait, explicitwait?

implicit wait explicit wait thread wait

1.Implicit Wait time is 1.Explicit Wait time is 1.threadwait,is an


applied to all the applied only to those instance method that’s
elements in the script. elements which are used for thread
intended by us. synchronization.

2.In Implicit Wait, we 2.In Explicit Wait, we • 2.It causes current


need not specify need to specify thread to wait until
"ExpectedConditions" on "ExpectedConditions" on either another thread
invokes the notify()
the element to be the element to be method or the
located. located. notifyAll() method for
this object.

3.It is recommended to 3.It is recommended to 3. It causes the thread


use when the elements use when the elements to pause for certain
are located with the time are located with the time number of milli
frame specified in implicit frame specified in seconds or until it
wait. implicit wait. is notified.

3.Syntax- 3.Syntax- 3.Syntax-


driver.manage().timeouts( WebDriverWait wait = ne
).implicitlyWait(10,TimeU w WebDriverWait(WebD Thread.sleep(2000)
nit.SECONDS) ; riverRefrence,TimeOut);
Example- Example-
WebDriverWait wait =
driver.manage().timeouts().pageLoadTi
1
meout(100, SECONDS); new
WebDriverWait(driver,
10);
WebElement element =
wait.until(ExpectedCondi
tions.elementToBeClicka
ble(By.id(>someid>)));
Q.27. What is fluent wait?
Fluent wait is used to define maximum amount of time to wait for a condition and also to
increase the frequency with which the conditions are checked. Using this type certain types
of exceptions such as “NoSuchElementExceptions” can be ignored too.

Syntax
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
//Wait for the condition
.withTimeout(30, TimeUnit.SECONDS)
// which to check for the condition with interval of 5 seconds.
.pollingEvery(5, TimeUnit.SECONDS)
//Which will ignore the NoSuchElementException
.ignoring(NoSuchElementException.class);

Q.28. How to handle drop down?


TO handle dropdown we need to use select class of selenium.
Select Class in Selenium
Models a SELECT tag, providing helper methods to select and deselect options. Select is a
class which is provided by Selenium to perform multiple operations on Dropdown
object and Multiple Select object. This class can be found under the Selenium’s
Support.UI.Select package. As select is also an ordinary class, so its object is also created
by a Newkeyword with regular class creation syntax.
Select oSelect = new Select(WebElement));
Different Select Commands to deal with Dropdown and Multi Select elements-

1.selectByVisibleText
selectByVisibleText(String arg0) : void – It is very easy to choose or select an
option given under any dropdowns and multiple selection boxes with
selectByVisibleText method. It takes a parameter of String which is one of the Value
of Select element and it returns nothing.

Command – oSelect.selectByVisibleText(“text”);

2.selectByIndex
selectByIndex(int arg0) : void – It is almost the same as selectByVisibleText but the
only difference here is that we provide the index number of the option here rather
the option text.It takes a parameter of int which is the index value of Select
element and it returns nothing.
Command – oSelect.selectByIndex(int);

selectByValue
selectByValue(String arg0) : void –It is again the same what we have discussed
earlier, the only difference in this is that it ask for the value of the option rather the
option text or index. It takes a parameter of String which is on of the value of Select
element and it returns nothing.
Command – oSelect.selectByValue(“text”);
4.getOptions
getOptions( ) : List<WebElement> –This gets the all options belonging to the Select
tag. It takes no parameter and returns List<WebElements>.
Command – oSelect.getOptions();

DeSelect Methods-
deselectAll( ) : void – Clear all selected entries. This is only valid when the SELECT
supports multiple selections.
Command – oSelect.deselectAll;
deselectByIndex(int arg0) : void –Deselect the option at the given index.

Command – oSelect.deselectByIndex;
deselectByValue(String arg0) : void –Deselect all options that have a value matching the
argument.

Command – oSelect.deselectByValue;
deselectByVisibleText(String arg0) : void – Deselect all options that display text matching
the argument.

Command – oSelect.deselectByVisibleText
isMultiple( ) : boolean – This tells whether the SELECT element support multiple
selecting options at the same time or not. This accepts nothing but returns
booleanvalue(true/false).
Command – oSelect.isMultiple();
Q.29. List out all methods available in select class.

Modifier and Type Method and Description

void deselectAll()
Clear all selected entries.

void deselectByIndex(int index)


Deselect the option at the given index.

void deselectByValue(java.lang.String value)


Deselect all options that have a value matching the ar

void deselectByVisibleText(java.lang.String text)


Deselect all options that display text matching the arg

java.util.List<WebElement> getAllSelectedOptions()

WebElement getFirstSelectedOption()

java.util.List<WebElement> getOptions()

boolean isMultiple()

void selectByIndex(int index)


Select the option at the given index.

void selectByValue(java.lang.String value)


Select all options that have a value matching the argu

void selectByVisibleText(java.lang.String text)


Select all options that display text matching the argum
Q.30. Low to capture all the value from dropdown?
To get all value from dropdown we need to use “getOptions()” method of select class.
Example-
WebElementselectElement = driver.findElement(By.id("s");
Select select = new Select(selectElement);
List<WebElement>allOptions = select.getOptions();

31)How to capture only selected value from drop down?

Ans: selectByVisibleText

Code – To select the value 2010.

Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));

oSelect.selectByVisibleText("2010");

selectByIndex

Code – To select the value 2010 using index.


Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));
oSelect.selectByIndex(4);

selectByValue

Code – To select the value 2014.


Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));
oSelect.selectByValue("2014");

32)How to capture non selected value from dropdown?


Ans: // Store all the elements of same category in the list of WebLements
List oRadioButton = driver.findElements(By.name("toolsqa"));
// Create a boolean variable which will hold the value (True/False)
boolean bValue = false;
// This statement will return True, in case of first Radio button is selected
bValue = oRadioButton.get(0).isSelected();
// This will check that if the bValue is True means if the first radio button is selected
if(bValue = true){
// This will select Second radio button, if the first radio button is selected by default
oRadioButton.get(1).click();
}else{
// If the first radio button is not selected by default, the first will be selected
oRadioButton.get(0).click();
}
33)How to how multiselect value from dropdown?

Ans: isMultiple
oSelect.isMultiple()
Select oSelect = new Select(driver.findElement(By.id(Element_ID)));
oSelect.selectByIndex(index)
34)How to select all the similar value from drop down Eg we have multiselect dropdown
like automation testing,manual testing sql testing we should all the option which
contains “testing”word?
Ans: By using select class Select by value method we can achive.
List<Webelement >listofdropdown=driver.findelements <by.id(“dropdown”));
Select select=new select(listofdropdown)
{
If(select.selectByvalue(“testing”)
{
System.out.println(list.getText());

35)How to work with custom select drop down/auto suggest dropdown?


Ans:
36) How to take mouse over operation on the element?
Ans Actions action = new Actions(webdriver);
WebElement we =
webdriver.findElement(By.xpath("//html/body/div[13]/ul/li[4]/
a"));
action.moveToElement(we).build().perform();

37)How to perform keyboard operation?


Ans: By using robot class
38) How to perform “control + c”
Ans: from selenium.webdriver.common.keys import Keys

elem = find_element_by_name("our_element")
elem.send_keys("bar")
elem.send_keys(Keys.CONTROL, 'a') #highlight all in box
elem.send_keys(Keys.CONTROL, 'c') #copy
elem.send_keys(Keys.CONTROL, 'v') #paste

I
39) Diffference between build() & perform()
Ans: Perform:: A convenience method for performing the actions without calling build()
first

To Perform Some Action you have to Call Build Before any Action like
click().build.perform(); // it is something like adding some Action to buffer from where
perform used to exceute that action

40) How to perform drag and drop operation?


Ans: public class DragNDropExample {
WebDriver driver;

@Test
public void testDragAndDropExample() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://jqueryui.com/droppable/");
//Wait for the frame to be available and switch to it
WebDriverWait wait = new WebDriverWait(driver, 5);

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelecto
r(".demo-frame")));
WebElement Sourcelocator = driver.findElement(By.cssSelector(".ui-
draggable"));
WebElement Destinationlocator = driver.findElement(By.cssSelector(".ui-
droppable"));
dragAndDrop(Sourcelocator,Destinationlocator);
String
actualText=driver.findElement(By.cssSelector("#droppable>p")).getText();
Assert.assertEquals(actualText, "Dropped!");
}
}
41. How to perform right click operation? Question on window handling
Answer: We can perform right click operation by using the context menu.
We will take the help of WebDriver action class and perform Right Click. The below is
the syntax :
Actions action = new Actions(driver).contextClick(element);
action.build().perform();

Below are the Steps we have followed in the example:


1. Identify the element
2. Wait for the presence of Element
3. Now perform Context click
4. After that we need to select the required link.

42. How to work with new tab, new browse window


Answer:
Tab is same like window. There is no difference with respect to selenium. There is
difference at code level, I mean HTML code level. But for selenium automation both are
the same.So, automating the new tab content is same like window.
You have to use switchTo().window()
Selenium uses this unique id to switch control among several windows. In simple
terms, each unique window has a unique ID, so that Selenium can differentiate when it is
switching controls from one window to the other.

• GetWindowHandle Command

Purpose: To get the window handle of the current window.

String handle= driver.getWindowHandle();//Return a string of alphanumeric window


handle

• GetWindowHandles Command

Purpose: To get the window handle of all the current windows.


Set<String> handle= driver.getWindowHandles();//Return a set of window handle

• SwitchTo Window Command

Purpose: WebDriver supports moving between named windows using the “switchTo”
method.

driver.switchTo().window("windowName");

Or
Alternatively, you can pass a “window handle” to the “switchTo().window()” method.
Knowing this, it’s possible to iterate over every open window like so:
for (String handle : driver.getWindowHandles()) {

driver.switchTo().window(handle);
}
• Switching between windows with Iterators:
driver.findElement(By.id(“id of the link which opens new window”)).click();
//wait till two windows are not opened
waitForNumberofWindowsToEqual(2);//this method is for wait
Set handles = driver.getWindowHandles();
firstWinHandle = driver.getWindowHandle(); handles.remove(firstWinHandle);
String winHandle=handles.iterator().next();
if (winHandle!=firstWinHandle){
//To retrieve the handle of second window, extracting the handle which does not match to
first window handle
secondWinHandle=winHandle; //Storing handle of second window handle
//Switch control to new window
driver.switchTo().window(secondWinHandle);

43. How to work with new tab new browse window with our GetWindowHandles
method?
Answer:You can switch between windows as below:
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window

// Close the new window, if that window no more required


driver.close();

// Switch back to original browser (first window)


driver.switchTo().window(winHandleBefore);

// Continue with original browser (first window)

44. How to handle alert pop-up


Answer:we can handle alert in Selenium Webdriver using Alert Interfaceand using
different methods.

Web-Based alert and Java Script alerts are same so do not get confused.
Until you do not handle alert window you cannot perform any action in the parent window.

Types of Alert Popup


Java scrip provides mainly following three types of alerts:
1. Simple 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.

2. Confirmation Popup
Confirmation popup displays on page of software web application with confirmation
text, Ok and Cancel button as shown In bellow given Image.
3. Prompt alertPopup

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

//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();

45.How to work calendar pop-up


Answer:
Calendar Pop Up is a type of Hidden Division Pop up. Since this pop up is a part of html
page we can use findElements() method and handle it.

In the web page sometimes you’ll fail to inspect a particular element, in that time, go to
firebug window in the firebug toolbar and select the firbug search symbol.
Here is an example which shows how to handle calendar pop up :

1) Launch Eclipse, create a project, a package, and a class under named “test1.java”.

2) Navigate to site “http://www.makemytrip.com/”. For this you need to add the following
lines of code in your script :
WebDriver driver=new FirefoxDriver();
driver.get(“http://www.makemytrip.com/”);

3) Right click on the calendar option given for Departure and inspect it. Chose the date of
departure as 3rd March. To do this much you need to include the following lines of code in
your script :

driver.findElement(By.id(“start_date_sec”)).click();
driver.findElement(By.xpath(“//*[@id=’ui-datepicker-
div’]/div[3]/table/tbody/tr[1]/td[3]/a”)).click();

4) Now again click on the Departure Calendar and click on the Cross button(X) to close the
calendar. For this, first locate the calendar and then click on it.

driver.findElement(By.id(“start_date_sec”)).click();
driver.findElement(By.xpath(“//*[@id=’ui-datepicker-div’]/div[5]/button[2]”)).click();
This is all about calendar pop up. Handling Calendar pop up is not complex. All you have
to do is locate the element and locate it correctly, then perform action…!!!
46. How to work with advertisement pop-up?
Answer:
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 webdriver software
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.
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;
public class unexpected_alert {
WebDriver driver = null;

@BeforeTest
public void setup() throws Exception {
System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
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();
}
}

47.How to work with SSl Pop-up?

Answer: Firstly, WHAT IS SSL CERTIFICATE ?

SSL is used to keep sensitive information which is sent across the Internet encrypted so
that only the intended recipient understand it. This is important because, the information
that we send on the internet is passed from one system to other system to the destination
server.

If it is not encrypted with an SSL certificate, any computer in between you and the
destination server can see your private information such as credit card numbers,
usernames, passwords and other sensitive information.

WHEN DO WE GET UNTRUSTED CONNECTION ERROR


When ever you try to visit a website whose web address starts with https, your
communication with this site is encrypted to ensure your privacy.
The certificate helps to determine whether the site you are visiting is actually the site that it
claims to be. If there is any problem with the certificate, you will see an alert saying 'This
Connection Is Untrusted'.
This is how the error looks like :

The below are the common errors that we see :


1. Certificate will not be valid until (date)
Error code: sec_error_expired_issuer_certificate
This error can occur if our system clock has the wrong date, check error message which
will be in the past. We can fix this problem, by setting system clock to current date.

2. Certificate expired on (date)


Error code: sec_error_expired_certificate
This error occurs when a website identity certification has expired. This can also occur if
system clock has the wrong date. We can fix this problem, by setting system clock to
current date.

3. Certificate is only valid for (site name)


Error code: ssl_error_bad_cert_domain
This error says that the identification sent to you by the site is actually for another site.
While anything you send would be safe from eavesdroppers , the recipient may not be the
same who you think it is.

The above listed errors are the common errors, you may come across other errors which
actually depends on the websites that you access.

Now Let us seehow to handle SSL Untrusted Connection and Accept with Selenium
webdriver. Let me try to do with Firefox browser
We will create new firefox profile and set 'setAcceptUntrustedCertificates' as true and
setAssumeUntrustedCertificateIssuer as false.
package com.example;
publicclassSSLExample {

private WebDriver driver;


@BeforeClass
publicvoidsetUp() {
//Creating new Firefox profile
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
driver = new FirefoxDriver(profile);
driver.manage().window().maximize();
}

@Test
publicvoidopenApplication() {
System.out.println("Navigating application");
driver.get("https://cacert.org/");
WebElement headingEle = driver.findElement(By.cssSelector(".story
h3"));
//Validate heading after accepting untrusted connection
String expectedHeading = "Are you new to CAcert?";
Assert.assertEquals(headingEle.getText(), expectedHeading);
}
@AfterClass
publicvoidtearDown() {
if(driver!=null)
driver.quit();
}
}
Done. You have now accepted the SSL Certificate with Selenium webdriver.

48. How to work with file download pop-up?

Answer:

How To Download Different Files Using Selenium WebDriver


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, etc.
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.

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


5. PDF File (.pdf) - application/pdf
6. CSV File (.csv) - text/csv
7. MS Excel File (.xlsx) - application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet
8. 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.
System.setProperty("webdriver.gecko.driver", "D:\\Selenium Files\\geckodriver.exe");
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.

• Downloading File Using AutoIt In Selenium WebDriver


We have to perform bellow given steps to create selenium webdriver + AutoIt script.
Identify objects properties of file download and save dialog
In Firefox browser, Go to THIS PAGE and click on "Download Text File" link. It will
open Save file dialog with Open with and Save File radio options.
Now you can Identify save file dialog properties using AutoIt Window Info tool as
described In THIS POST. In this case you will get only dialog's property (Title and class)
using AutoIt Window Info tool as shown In bellow Image. It Is not able to retrieve
property of Save File radio option and OK button. So we have to use some alternative
method In our AutoIt script to select Save File radio option and click OK button.

So we have only dialog property In this case as bellow.

• File Save dialog : Title = Opening Testing Text.txt, Class = MozillaDialogClass


We will use class property In our script to select dialog.

Write AutoIt script to save file


If you see In above Image, Save File option has shortcut to select It. We can select It using
ALT + S keyboard shortcut keys. Also focus Is set by default on OK button. So we can press
ENTER key to select OK. We can do both these Keystroke action In AutoIt very easily using
Send() command as shown In bellow script.

; wait for 8 seconds to appear download and save dialog. Used class property of
download dialog.
WinWait("[CLASS:#MozillaDialogClass]","",8)

; Perform keyboard ALT key down + s + ALT key Up action to select Save File Radio
button using keyboard sortcut.
Send("{ALTDOWN}s{ALTUP}")

; Wait for 3 seconds


Sleep(3000)

; Press Keyboard ENTER button.


Send("{ENTER}")

Save above script In "Script To Download File.au3" format at "E:\AutoIT" location.


Above script will perform bellow give actions.

1. wait for 8 seconds to appear file saving dialog.


2. Press ALT down + s + ALT up key to select Save File radio.
3. Press Enter key to select OK button.
Convert script In executable format

Now you can create executable file of above script as described In THIS POST. After
conversion, you will get executable file "Script To Download File.exe".

CLICK HERE to download ready made "Script To Download File.au3" and "Script To
Download File.exe" files of AutoIt.

Integrate AutoIt script with selenium webdriver to download file


As described In THIS POST, We will use java Runtime.getRuntime().exec(); method to
execute AutoIt script In selenium webdriver.

So our Selenium webdriver + AutoIt script to download file from web page Is as bellow.
Note : "Script To Download File.exe" file should be located at E:\\AutoIT folder.
package AutoIt;

import java.io.IOException;
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.BeforeTest;
import org.testng.annotations.Test;

public class AutoIt_Test {


WebDriver driver;

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

@Test
public void testCaseOne_Test_One() throws IOException, InterruptedException {
//Click on Download Text File link to download file.
driver.findElement(By.xpath("//a[contains(.,'Download Text File')]")).click();
//Execute Script To Download File.exe file to run AutoIt script. File location =
E:\\AutoIT\\
Runtime.getRuntime().exec("E:\\AutoIT\\Script To Download File.exe");
}
}

Now If you run above script, It will download Text file automatically. At the end of script
execution, file will be downloaded as shown In bellow Image.

This way you can download any file from web page.

49.How to handle file upload pop-up using AutoIT?


Answer:
50.How to handle file upload pop-up using robot classes?
Answer:
Robot class is used to (generate native system input events) take the control of mouse and
keyboard. Once you get the control, you can do any type of operation related to mouse and
keyboard through with java code.

There are different methods which robot class uses. Here in the below example we have
used 'keyPress' and 'keyRelease' methods.

keyPress - takes keyCode as Parameter and Presses here a given key.


keyrelease - takes keyCode as Parameterand Releases a given key

Both the above methods Throws - IllegalArgumentException, if keycode is not a valid key.

We have defined two methods in the below example along with the test which is used to
upload a file.

public class UploadFileRobot {


String URL = "application URL";
@Test
public void testUpload() throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.get(URL);
WebElement element = driver.findElement(By.name("uploadfile"));
element.click();
uploadFile("path to the file");
Thread.sleep(2000);
}
* This method will set any parameter string to the system's clipboard.
*/
public static void setClipboardData(String string) {
//StringSelection is a class that can be used for copy and paste operations.
StringSelection stringSelection = new StringSelection(string);

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection,
null);
}
public static void uploadFile(String fileLocation) {
try {
//Setting clipboard with file location
setClipboardData(fileLocation);
//native key strokes for CTRL, V and ENTER keys
Robot robot = new Robot();

robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
} catch (Exception exp) {
exp.printStackTrace();
}
}
}

51. How to handle browser scroll bar?


There are two ways:
1. JavascriptExecutor JSE = (JavascriptExecutor) driver;
JSE. executeScript("scroll(0,250)");

OR
• Using JAVA script executor
1. We can scroll down vertically by using the following code:
2. ((JavascriptExecutor) driver).executeScript("scroll(0,250);");
3. Similarly, it is also possible to scroll up by changing y coordinate as
negative:
4. ((JavascriptExecutor) driver).executeScript("scroll(0, -250);");

5. You can also use the following code: For scroll down:

6. ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,250)", "");

• Using ROBOT class we can generate key event.


• Using chord also we can handle scroll bar.

52. How to execute java script?


JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium
Webdriver.

53. How to work with frame window?


→by following three ways we can work…
• driver.switchTo.frame(0): Pass the frame index and driver will switch to that frame.
• driver.switchTo.frame(“frame1”): Pass the frame element Name or ID and driver will
switch to that frame.
• driver.switchTo.frame(frameElement): Pass the frame web element and driver will
switch to that frame.

54. How to work with nested frame?


→Some times when there are multiple Frames (Frame inside a frame), we need to first
switch to the parent frame and then we need to switch to the child frame.

driver.switchTo().frame(outer frame).switchTo().frame(inner frame);

55. How to work with multiple frames?


→ d.switchTo().frame(0);
d.findElement(By.id(“recaptcha - anchor”)).click();

d.switchTo().defaultContent();

d.switchTo().frame(1);
Or
55. How to work with multiple windows?
We can handle multiple windows in selenium webdriver using “Switch To” methods
which will allow us to switch control from one window to another window.
String parent=driver.getWindowHandle();
Set<String>s1=driver.getWindowHandles();
Iterator<String> I1= s1.iterator();
while(I1.hasNext())
{
String child_window=I1.next();
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close();
}
}
//First we will find the iFrame , then we will switch to command.
WebElement frame = driver.findElement(By.Name("frame1"));
//Now we will switch focus,
driver.switchTo().frame("frame");
56. How many ways to work with frames?
→Following are the possible ways for handling Frames

A] If Frame is having the element properties like name/value

webdriver.switchTo().frame("frame name/value");

B] If Frame is having index

webdriver.switchTo().frame(index);

C] If the Frame Properties or changing dynamically / if u want to perform using


frame xpath / css path
webdriver.switchTo().frame(webdriver.findElement(By.xpath(elementxpath));
webdriver.switchTo().frame(webdriver.findElement(By.cssSelector(elementcsspath
));

Note: finally if you want to make operation out of the frame first you need get out of
the frame following is the statement for that
driver.switchTo().defaultContent();
57. How to work on frame, if we don’t have ID or Web Element
→ we must find the index of the iframe through which the element is being loaded
and then we need to switch to the iframe through the index.
int size = driver.findElements(By.tagName("iframe")).size();

the above code finds the total number of iframes present inside the page using the
tagname 'iframe'.
Now, finding out the index of iframe.
for(int i=0; i<=size; i++){
driver.switchTo().frame(i);
int total=driver.findElements(By.xpath("html/body/a/img")).size();
System.out.println(total);
driver.switchTo().defaultContent();
}
58. What is illegal state exception?

59. How to work with IE Browser?

→Path to the folder where you have extracted the IEDriver executable file
String service = "D:\\ToolsQA\\trunk\\Library\\drivers\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", service);
InternetExplorerDriver driver = new InternetExplorerDriver();
driver.get("http://demoqa.com");
60. How to write xpath in IE and Chrome browser?
→ Step #1: For creating XPath in Developer tool, open the console tab.
Step #2: Type the created Xpath and enclose it in $x(“//input[@id=’Email’]”)

Q.91 What is role of Maven Framework?

➢ Maven is used to define project structure, dependencies, build, and test


management.
➢ Using pom.xml (Maven) you can configure dependencies needed for building
testing and running code.
➢ Maven automatically downloads the necessary files from the repository while
building the project.

Fig.Maven project structure


Q.92What is dependencies, how to handle dependencies in a framework?

➢ Maven’s dependency is a mechanism which helps to download all the necessary


dependency libraries for the project automatically, and maintain the version upgrade
as well.
➢ Handle dependencies 1.Create Maven project.
2. Open pom.xml
3. Under the ‘project’ tag add <dependencies> as
another
tag, and google for the Maven dependencies.
4. So after getting the dependency create another
tag dependency inside <dependencies> tag.

Q.93What is POM (Project Object Model)?

➢ A Project Object Model or POM is the fundamental unit of work in Maven. It is an


XML file.
➢ The pom.xml file contains information of project and configuration information for
the maven to build the project such as dependencies, build directory, source
directory, test source directory, plugin, goals etc.

Q.94Explain the maven plugin you used in your framework?

Maven plugins are used to


• Create a jar file
• Create war file
• Compile code files
• Unit testing of code
• Documenting projects.
• Reporting.

The plug-ins available in “org/apache/maven/plugins”, list as follow’s

Clean- Clean up after the build.

Compiler - Compiles Java sources.

Deploy - Deploy the built artifact to the remote repository.

Failsafe - Run the JUnit integration tests in an isolated classloader.

Install - Install the built artifact into the local repository.

Resources - Copy the resources to the output directory for including in the JAR.

Site - Generate a site for the current project.

Surefile - Run the JUnit unit tests in an isolated classloader.

Verifier - Useful for integration tests - verifies the existence of certain conditions.

Q.95How to execute testng.xml in maven pom.xml?

Step 1: First create a maven project

Step 2: Create a class

Step 3: Add Tests in a class (annotations)


Step 4: Add TestNG and Selenium Dependencies to maven pom.xml file.

Step 5: Now add maven Surefire Plug-in to pom.xml

Step 6: Execute tests using 'mvn test' from command prompt.

4. JENKINS

Q.96What is Jenkins?

➢ Jenkins is software that allows continuous integration server or tool


➢ It provides Continuous Integration services for software development, which can
be started via command line or web application server.
➢ Jenkins is a self-contained, open source automation server which can be used to
automate all sorts of tasks such as building, testing and deploying software.

Fig. Jenkins work flow diagram


➢ Key Features of Jenkins
• It will Generate test reports
• Jenkins can Integrate with many different Version Control Systems
• Jenkins will Deploys directly to production or test environments and many
more.

Q.97What is the role of Jenkins in a framework?


Jenkins is automation tool to automate anything including build, deployment, test
automation, reporting.
You can even use jenkins to do any automation task other then build, deployment, test like
• running script on remote machine
• taking backups
• performing health check
The beauty of jenkins is its plugin based architecture. You can plugin in anything you want
and get things working. If you do not want you can remove plugin and save memory and
optimize your jenkins application.
• You can run your testing automation on destination machine via jenkins remotely.
• You can generate testing report.
• You can make threshold as per test cases.
• Send the notification of your test report.
• schedule your automation at midnight.
• Can associate jenkins with a version control server.
• Can trigger builds by polling, Periodic etc.
• Can execute bash scripts, shell scripts, ANT and Maven Targets
• Can Publish results and send email notifications

Q.98What is the advantages of Jenkins?


➢ It is open source and it is user-friendly, easy to install and does not require
additional installations or components.
➢ It is free of cost.
➢ Easily Configurable. Jenkins can be easily modified and extended. It deploys code
instantly, generates test reports. Jenkins can be configured according to the
requirements for continuous integrations and continuous delivery.
➢ Platform Independent. Jenkins is available for all platforms and different operating
systems, whether OS X, Windows or Linux.
➢ Rich Plugin ecosystem. The extensive pool of plugins makes Jenkins flexible and
allows building, deploying and automating across various platforms.
➢ Easy support. Because it is open source and widely used, there is no shortage of
support from large online communities of agile teams.
➢ Developers write the tests to detect the errors of their code as soon as possible. So
the developers don’t waste time on large-scale error-ridden integrations.
➢ Issues are detected and resolved almost right away which keeps the software in a
state where it can be released at any time safely.
➢ Most of the integration work is automated. Hence fewer integration issues. This
saves both time and money over the lifespan of a project.

Q.99How to configure Jenkins?


Requirements
• Java 7 or Java 8 must be installed.
• Requires minimum RAM of 512MB
Steps
➢ Download Jenkins.war.
➢ Check Java is installed or not by typing java -version command in command
prompt.
➢ Open up a terminal in the download directory and run java -jar jenkins.war
➢ Browse to http://localhost:8080 and enter highlated password to continue the
installation.
➢ Next it will takes you to “Create First Admin User”, provide details &finish.
➢ It will opens the Jenkins Home page

Q.100 Difference between Xpath and cssSelector?

Xpath
Xpath is a query language for selecting nodes from an XML document.While DOM is the
recognized standard for navigation through an HTML element tree, XPath is the standard
navigation tool for XML.XPath is used everywhere where there is XML. XPath is a very
powerful language to express which element to identify.If you use it correctly, it can
produce very reliable and low maintenance locators, but if you use it incorrectly, it can
create very brittle test cases.
Pros:
–Allows very precise locators
Cons:
–Slower than CSS
–Relies on browser’s XPath implementation which is not always complete (especially on
IE) and as such is not –recommended for cross-browser testing.
Absolute path:
driver.findElement(By.xpath("html/body/div/p/input"));

Relative path:
driver.findElement(By.xpath("input"));

ccsSelector

The CSS locator strategy uses CSS selectors to find the elements in the page. Selenium
supports CSS 1 through 3 selectors syntax excepted CSS3 namespaces.Browsers
implement CSS parsing engines for formatting or styling the pages using CSS syntax.
Pros:
–Much faster than XPath
–Widely used
–Provides a good balance between structure and attributes
–Allows for selection of elements by their surrounding context
Cons:
–They tend to be more complex and require a steeper learning curve.

Examples:
Absolute Path:
driver.findElement(By.cssSelector("html>body>div>p>input"));
Relative Path:
driver.findElement(By.cssSelector("input"));
Regular Attribute:
driver.findElement(By.cssSelector("button[name='cancel']")); (tag with attribute value)

You might also like