Top Selenium Interview Questions with Framework Examples




TOP Selenium Interview Questions for Freshers and Experienced People


Q #1) Why should Selenium be selected as a test tool?
Selenium
Ø  is free and open source
Ø  have a large user base and helping communities
Ø  have cross Browser compatibility (Firefox, chrome, Internet Explorer, Safari etc.)
Ø  have great platform compatibility (Windows, Mac OS, Linux etc.)
Ø  supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
Ø  has fresh and regular repository developments
Ø  supports distributed testing

Q #2) 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 the user to create test scripts in the 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 #3) What are the testing types that can be supported by Selenium?

Selenium supports the following types of testing:
Ø  Functional Testing
Ø  Regression Testing

Q #4) 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 Barcode 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 #5) What is the difference between Selenium IDE, Selenium RC and WebDriver?

Feature
Selenium IDE
Selenium RC
WebDriver

Browser Compatibility
Selenium IDE comes as a Firefox plugin, thus it supports only Firefox
Selenium RC supports a varied range of versions of Mozilla Firefox, Google Chrome, Internet Explorer and Opera
WebDriver supports a varied range of versions of Mozilla Firefox, Google Chrome, Internet Explorer and Opera.
Also supports HtmlUnitDriver which is a GUI-less or headless browser. 
Record and Playback
Selenium IDE supports record and playback feature
Selenium RC doesn't support record and playback feature
WebDriver doesn't support record and playback feature
Server Requirement
Selenium IDE doesn't require any server to be started before executing the test scripts
Selenium RC requires server to be started before executing the test scripts
WebDriver doesn't require any server to be started before executing the test scripts
Architecture
Selenium IDE is a JavaScript based framework
Selenium RC is a JavaScript based Framework
WebDriver uses the browser's native compatibility to automation
Object Oriented
Selenium IDE is not an object oriented tool
Selenium RC is semi object oriented tool
WebDriver is a purely object-oriented tool
Dynamic Finders
(for locating web elements on a web page)
Selenium IDE doesn't support dynamic finders
Selenium RC doesn't support dynamic finders
WebDriver supports dynamic finders
Handling Alerts, Navigations, Dropdowns
Selenium IDE doesn't explicitly provides aids to handle alerts, navigations, dropdowns
Selenium RC doesn't explicitly provides aids to handle alerts, navigations, dropdowns
WebDriver offers a wide range of utilities and classes that help in handling alerts, navigations, and dropdowns efficiently and effectively.
WAP (iPhone/Android) Testing
Selenium IDE doesn't support testing of iPhone/Android applications
Selenium RC doesn't support testing of iPhone/Android applications
WebDriver is designed in a way to efficiently support testing of iPhone/Android applications. The tool comes with a large range of drivers for WAP based testing.
For example, AndroidDriver, iPhoneDriver 
Listener Support
Selenium IDE doesn't support listeners
Selenium RC doesn't support listeners
WebDriver supports the implementation of Listeners
Speed
Selenium IDE is fast as it is plugged in with the web-browser that launches the test. Thus, the IDE and browser communicate directly
Selenium RC is slower than WebDriver as it doesn't communicate directly with the browser; rather it sends selenese commands over to Selenium Core which in turn communicates with the browser.
WebDriver communicates directly with the web browsers. Thus making it much faster.

Q #6) 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 make it exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.
Q #7) What is Selenese?

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

Q #8) What are the different types of locators in Selenium?
The locator can be termed as an address that identifies a web element uniquely within the web page. 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 #9) What is the 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 halt i.e. any failure during verification would not stop the execution and all the test steps would be executed.

Q #10) What is XPath? When should you use XPath in Selenium?

XPath is a way to navigate in an HTML/XML document and this can be used to identify elements in a web page. You may have to use XPath when there is no name/id associated with an element on the page or only a partial part of name/id is constant.

Direct child is denoted with – /
Relative child is denoted with – //

Id, class, names can also be used with XPath –
Ø  //input[@name=’q’]
Ø  //input[@id=’lst-ib’]
Ø  //input[@class=’ lst’]
If only part of id/name/class is constant than “contains” can be used as –
Ø  //input[contains(@id,’lst-ib’)]

Q #11) 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 #12) 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 #13) 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 #14) Which is the latest Selenium tool?

WebDriver
Q #15) 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();



Join the “Top Rated Best Selenium Course” – Basics To Advanced Level With  Grid, Maven, Jenkins, Interviews at https://goo.gl/zCW8Fs
Q #16) 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 #17) What are the different 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 #18) How to type in a text box using Selenium?

The user can use sendKeys(“String to be entered”) to enter the string in the textbox.

Syntax:
WebElement username = driver.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);

Q #19) 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”)).isSelected();
isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();

Q #20) 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 #21) How to select a value in a dropdown?

The value in the drop down can be selected using WebDriver’s Select class.

Syntax:
selectByValue:
Select selectByValue = new Select(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 = new Select(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);

Q #22) 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 web page in the web browser’s history.

Sample code:
driver.navigate().back();

navigate().forward() – This command lets the user 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 refresh the current web page thereby reloading all the web elements.

Sample code:
driver.navigate().refresh();

navigate().to() – This command lets the user launch a new web browser window and navigate to the specified URL.

Sample code:
driver.navigate().to(“https://google.com”);

Q #23) How to click on a hyperlink 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 finds 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 #24) How to handle frame in WebDriver?

An inline frame acronym as iframe is used to insert another document within 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)
driver.switchTo().frame(driver.findElement(By.id("IF1")));
Select Parent Window
driver.switchTo().defaultContent();

Q #25) 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.findElement(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 #26) How to find more than one web element in the list?

At times, we may come across elements of the 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:

// Storing the list
List<WebElement> elementList = driver.findElements(By.xpath("//div[@id='example']//ul//li"));
// Fetching the size of the list
int listSize = elementList.size();
for (int i=0; i<listSize; i++)
{
            // Clicking on each service provider link
            serviceProviderLinks.get(i).click();
            // Navigating back to the previous page that stores link to service providers
            driver.navigate().back();
}

Q #27) 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 the 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 #28) 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 #29) 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 #30) 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 #31) How to assert the 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”));

#32) How to perform Mouse over action on the submenu item of a header menu?

With the actions object you should first move the menu title, and then move to the popup menu item and click it. Don’t forget to call actions.perform() at the end. Here’s some sample Java code:

Sample Code:
Actions actions = new Actions(driver);

WebElement menuHoverLink = driver.findElement(By.linkText("Menu heading"));

actions.moveToElement(menuHoverLink);

WebElement subLink = driver.findElement(By.cssSelector("#headerMenu .subLink"));

actions.moveToElement(subLink);

actions.click();

actions.perform();


Q #33) 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 #34) How to capture screenshot in WebDriver?

Sample Code:
// Code to capture the screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Code to copy the screenshot in the desired location
FileUtils.copyFile(scrFile, new File("C:\\CaptureScreenshot\\google.jpg"));


Q #35) What is the difference between Selenium and QTP?

Feature
Selenium
Quick Test Professional (QTP)
Browser Compatibility
Selenium supports almost all the popular browsers like Firefox, Chrome, Safari, Internet Explorer, Opera etc
QTP supports Internet Explorer, Firefox and Chrome. QTP only supports Windows Operating System
Distribution
Selenium is distributed as an open source tool and is freely available
QTP is distributed as a licensed tool and is commercialized
Application under Test
Selenium supports testing of only web based applications
QTP supports testing of both the web based application and windows based application
Object Repository
Object Repository needs to be created as a separate entity
QTP automatically creates and maintains Object Repository
Language Support
Selenium supports multiple programming languages like Java, C#, Ruby, Python, Perl etc.
QTP supports only VB Script
Vendor Support
As Selenium is a free tool, user would not get the vendor’s support in troubleshooting issues
Users can easily get the vendor’s support in case of any issue

Q #36) 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 #37) Can captcha be automated?

No, captcha and bar code reader cannot be automated.
Q #38) 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.
Q #39) What is CSS locator strategy in Selenium? Explain with example.

CSS location strategy can be used with Selenium to locate elements, it works using cascade style sheet location methods in which –

Direct child is denoted with – (A space symbol)
Relative child is denoted with – >

Id, class, names can also be used with XPath –
Ø  css=input[name=’q’]
Ø  css=input[id=’lst-ib’] or input#lst-ib
Ø  css=input[class=’lst’] or input.lst
If only part of id/name/class is constant than “contains” can be used as –
Ø  css=input[id*=’lst-ib’)]
Element location strategy using inner text
Ø  css = a:contains(‘log out’)


Q #40) There are many locators like id, name, XPath, CSS locator, which one should I use?

If there are unique names or identifier available, then they should be used instead of XPath and CSS locators. If not, then CSS locators should be given preference as their evaluation is faster than XPath in most modern browsers.

Q #41) How can I address SSL Certificate issue in Firefox with WebDriver (or) how to manage the secured connection error in HTTPS?

FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
driver=new FirefoxDriver(profile);

Q #42) How can I fix SSL certification issue in IE?

// Add the below command after opening the browser.
<strong>driver.navigate().to(“javascript:document.getElementById(‘overridelink’).click()”);</strong>

Q #43) 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?

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]
Q #44) Can you tell me a difference between driver.get() and driver.navigate() methods?
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 navigating 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.

Q #45) Can you tell me the syntax to set browser window size to 500(Width) X 500(Height)?
We can set browser window size using setSize method of the selenium web driver software testing tool. To set size at 800 X 600, Use below given syntax in your test case.

driver.manage().window().setSize(new Dimension(500,500));

Q #46) Can you tell me the usage of "submit" method in selenium WebDriver?
We can use submit method to submit the forms in the selenium WebDriver software automation testing tool. Example: Submitting registration form, submitting Login form, submitting Contact Us form etc. After filling all required fields, we can call submit method to submit the form. submit() method works same as clicking on submit button.

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.



 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.

Q #47) On Google search page, I want to search for some words without clicking on Google Search button. Is It Possible in WebDriver? How?
Yes, we can do It using WebDriver sendKeys method where we do not need to use Google Search button. Syntax is as below.
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.

Q #48) Can you tell me two drawbacks of xPath locators as compared to cssSelector locator?
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.

Q #48) Tell me a scenario which we cannot automate in selenium WebDriver.
Ø  Bitmap comparison Is not possible using selenium webdriver software testing tool.
Ø  Automating captcha Is not possible
Ø  We cannot read bar code using selenium web driver software testing tool.


Q #49) Tell me any 5 web driver common exceptions which you faced during software test case execution.

WebDriver's different 5 exceptions are as bellow.

Ø  TimeoutException - This exception will be thrown when command execution does not complete in given time.
Ø  NoSuchElementException - WebDriver software testing tool will throw this exception when element could not be found on page of software web application.
Ø  NoAlertPresentException - This exception will be generated when web driver ties to switch to alert popup but there Is not any alert present on page.
Ø  ElementNotSelectableException - It will be thrown when web driver Is trying to select unselect able element.
Ø  ElementNotVisibleException - Thrown when web driver Is not able to Interact with element which Is Available in DOM but It Is hidden.

Looking for Training on Selenium with C# online Training .. Register with us for Free Demo.


Q #50) Tell me different ways to verify element present or not on page.
We can check If Element is present or not on page of software we application using below 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
Q #51) Explain how you can login into any site if it’s showing any authentication popup for password and username?
Pass the username and password with url
Syntax-http://username:password@url

Q #51) Explain using Webdriver how you can perform double click?
You can perform double click by using
Syntax- Actions act = new Actions (driver);
act.doubleClick(webelement);

Q #52) Can we enter text without using sendKeys()?
Yes, we can enter text without using sendKeys() method. We have to use combination of javascript and wrapper classes with WebDriver extension class, check the below code-

WrapsDriver wrappedElement = (WrapsDriver) element;
JavascriptExecutor driver = (JavascriptExecutor)wrappedElement.getWrappedDriver();
driver.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])", element, attributeName, value);

Q #53) What is the name of Headless browser?
HtmlUnitDriver
Sample Code:
HtmlUnitDriver driver = new HtmlUnitDriver(true);
driver.setJavascriptEnabled(false);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.google.co.in/");
System.out.println(driver.getTitle());




Q #54) How do you send ENTER/TAB keys in WebDriver?

use click() or submit() [submit() can be used only when type=’submit’]) method for ENTER. Or use Actions class to press keys.
For Enter- act.sendKeys(Keys.RETURN);
For Tab- act.sendKeys(Keys.ENTER);
where act is Actions class type. (Actions act = new Actions(driver);)

Q #55) How to check all checkboxes in a page?

List<WebElement> chkBox = driver.findElements(By.xpath(“//html[@attribute='checkbox']”));
for  (int i=0; i<chkBox.size(); i++){
chkBox.get(i).click();
}

Q #56) How to execute java scripts function?

JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("pass your java scripts");

Q #57) How to count total number of rows of a table using Selenium 2.0?

List <WebElement> rows = driver.findElements(By.xpath("//table[@id='tableID']/tr"));
int totalRow = rows.size();

Q #58) How to store page source using Selenium 2.0?

String pagesource = driver.getPageSource();

Q #59) How to get element attribute using Selenium 2.0?

WebElement el = driver.findElement(By.id("ElementID"));
//get text from element and stored in text variable
String attributeValue = el. getAttribute("AttributeName");

Q #60) How to perform drag and drop in selenium 2.0?

WebElement source = driver.findElement(By.id("Source ElementID"));
WebElement destination = driver.findElement(By.id("Taget ElementID"));

Actions builder = new Actions(driver);
builder.dragAndDrop(source, destination ).perform();

For Selenium with Python online Training  .Register For Free Demo.


Selenium WebDriver methods with Examples

1. Browser Back and Forward (NAVIGATION)

Steps to implement Browser back and forward through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Navigate to some page in website.
4. Use Selenium code to Navigate Back to Main Page.

CODE: driver.navigate().back();
           driver.navigate().forward();

Example:
WebDriver driver =new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000); //delay
driver.navigate().back();
driver.navigate().forward();

2.Handling DRAG and DROP

Steps to Handle Drag and Drop through Selenium Web Driver
1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Create an Action object for Driver
4. Fetch and create WebElement object for the SOURCE element.
5. Fetch and create WebElement object for the DESTINATION element.
6.Perform ACTION
a.       Click and Hold the source WebElement
b.      Move to destination WebElement
c.       Release the Element.

Example:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.ericbieller.com/examples/dragdrop/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Actions act = new Actions(driver);
WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement des = driver.findElement(By.id("trash"));

act.clickAndHold(src).build().perform();     //For each action we need to build and Perform
act.moveToElement(des).build().perform();
act.release(des).build().perform();



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

Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Create a Select object for the Drop Down Element object.
5. Create a List and collect all Options through Select Object.
6. Create an Iterator object for the List.
7. Get the size of the List.
8. Loop through and check for required element.

Example:

WebElement element = driver.findElement(By.name("selectedCustomer"));
Select dd= new Select(element);
List allOptions= dd.getOptions(); 

//To go through the list, we can use an Iterator.
//Iterator should be of the same type as the List
//which is WebElement in this case. 

Iterator it = allOptions.iterator();
//Using while loop, we can iterate till the List has
//a next WebElement [hasNext() is true]
//number of items in the list
System.out.println(allOptions.size());

while(it.hasNext()){
//When you say it.next(), it points to a particular
//WebElement in the List.
WebElement el = it.next();
 //Check for the required element by Text and click it
if(el.getText().equals("mango")){
  System.out.println(el.getAttribute("value"));
   el.click();   
 }
}
4.Making Single Select in Drop down (By INDEX, VALUE, TEXT)

Steps to make Single Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by INDEX
6. Select by VALUE
7. Select by VISIBLE TEXT

Example:

WebElement customerdd = driver.findElement(By.name("customerProject.shownCustomer"));
  //convert the element to select object
  Select cust = new Select(customerdd);
  cust.selectByIndex(1);        //Select by Index
  Thread.sleep(3000);
  cust.selectByValue("2");   //Select by Value
  Thread.sleep(3000);
  cust.selectByVisibleText("mango");  //Select by Visible Text

5.Multiple Select List Box Window
Steps to make Multiple Select in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)

Example:

WebElement userdd = driver.findElement(By.name("users"));
Select usr = new Select(userdd);
usr.selectByIndex(0);                     //Select by Index(From Start location)
usr.selectByIndex(2);                     //Select by index(To End Location)

6.Multiple Select List Box Window - DESELECT
Steps to make Deselect in Drop down through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Drop Down element and create an object as WebElement.
4. Convert the Drop Down Element in to Select object.
5. Select by Index(Start index)
6. Select by Index(End index)

Example:

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

//You can deselect the options
usr.deselectAll();                                          //Deselect ALL selected elements
//or 
usr.deselectByIndex(0);                              //Deselect By using Index
//or
usr.deselectByValue(value);                       //Deselect By using Value
//or
usr.deselectByVisibleText(text);                 //Deselect By using Text

7.iFRAMES - How to handle Frames in Web Driver

Steps to get Source of each iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Loop though and print the Source of each Frame

Example:
/*times of india website - multiple frames*/

driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

List frms= driver.findElements(By.tagName("iframe"));  //Frame List
System.out.println(frms.size());
for (int i=0;i< frms.size();i++)
{
 System.out.println(frms.get(i).getAttribute("src"));
}

8.iFRAMES - How to perform action in Frames

Steps to perform Action in iFrame through Selenium Web Driver.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch iFrame element and create a Web Element object.
4. Using iFrame Web Element object, switch to IFrame.
5. Perform SendKeys/ Click action in iFrame.

Example:
WebElement ifr = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));
driver.switchTo().frame(ifr);                                     //Switch to iFrame
driver.findElement(By.id("mathuserans2")).sendKeys("8");  //Perform Action in iFrame

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

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

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Make a List containing FRAME web elements of a Web Page.
4. Get the Size of Frames.
5. Switch to required iFrame through index.

Example:

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

List frms= driver.findElements(By.tagName("iframe"));
System.out.println(frms.size());
driver.switchTo().frame(0);
driver.findElement(By.id("clicktripad")).click();

10. TABS / New Window

When Browser opens in a new window or in a new tab, Web Driver cannot shift the control to the new Window/ Tab. We need to collect the window handles in a page. Whenever a new window opens we need to iterate and shift to the latest window handle.

TABS/New Window - 1
Steps to iterate through the Window Handles

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. At First iterator will not be pointing to any Window Handle, only First Increment Points to First Window Handle, Second increment Points to second iterator.

Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
while(it.hasNext())
{
 System.out.println(it.next());
}
TABS/New Window - 2

When two browsers are opened and Web Driver need to shift the control from Parent Window to Child Window.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.

Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();

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

TABS/New Window - 3

When second browser is closed/you close it and Web Driver need to shift the control from Child Window to Parent Window.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Collect Window Handles through Set
4. Create an iterator to iterate through Window Handles.
5. Increment the iterator and store the Window Handle as Parent.
6. Increment the iterator and store next Window Handle as Child.
7. Switch to Child Browser using Child Window Handle.
8. When Child browser get closed, Switch from Child browser to Parent Window.

Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();

String parentBrowser= it.next();
String childBrowser = it.next();
driver.switchTo().window(childBrowser);
Thread.sleep(3000);

driver.close();         //close the current  window(Child Browser)
driver.switchTo().window(parentBrowser);          //Switch to Parent Browser

11. CALENDAR popups

Calendar PopUp - 1

Normal Calender(current month) Popup can be handled in the following way.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the Calender element and click to open.
4. Fetch the required date through xpath and click.


/*IRCTC calendar*/
driver.findElement(By.id("calendar_icon1")).click(); 
driver.findElement(By.xpath("//div[@id='CalendarControl']/table[tbody[tr[td[text()='October 2012']]]]/descendant::a[text()='5']")).click();

Calendar PopUp - 2 (Customized wait)

 In a Calender if we want to click on future month which is not currently displayed, we need to click on next link until we get the required month.
           This can be done by writing Customized wait. Check for particular date element in each month, if not found move to next month.

/*makemytrip calendar*/
driver.get("http://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("deptDateRtripimgExact")).click(); //find Calendar
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
boolean flag=true;
while(flag) {
  try {
 WebElement el = driver.findElement(By.xpath("//div[contains(@class,'ui-datepicker-group') and descendant::span[text()='March']]/descendant::a[text()='5']")); // Required future date
 if(el !=null)   //Check if the required date element is found or not
       {
  el.click(); // if required Date is found, then click  the date
  flag=false;
 }
    }
catch (Exception e) { //Catches exception if no element found
try {
 Thread.sleep(500);
 driver.findElement(By.xpath("//a[@title='Next']")).click(); //Click on next month
 }
catch (InterruptedException e1)
      {
 // TODO Auto-generated catch block
  e1.printStackTrace();
      }
  }
}

12. Drop Down MENU

In order to click on a menu item, first we need to move the mouse over Parent menu, later we can click on any of the Menu child item.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla)
2. Go to the URL
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action object for Driver
5. Through Action object, move to Parent element.
6. Give a Delay for menu items to be displayed.
7. Fetch the Child item through xpath and Click on it.


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

13. Context Click (Right Click)

We can use keyboard keys to Make a Right Click.

Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the MENU Parent element and create a WebElement object.
4. Create an Action Object for Driver.
5. Through Action Object, make a Context Click on Menu Parent object.
6. Through Action Object, send keys for ARROW_DOWN/ARROW_UP/Keys.ENTER.

Example:

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

Actions act = new Actions(driver); //Create Action object for Driver

act.contextClick(parentMenu).build().perform(); //Context Click

act.sendKeys(Keys.ARROW_RIGHT).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ARROW_DOWN).build().perform();
Thread.sleep(1000);
act.sendKeys(Keys.ENTER).build().perform();


14. JAVA SCRIPT example

We can use java script command to perform actions.
We can write code to fill up the text box through java script.

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Create Java Script executor object for the Driver.
4. Store the Java Script command in a String Variable.
5. Java Script Executor object executes the command in the Variable.

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

15. Multiple Elements

We can count the number of links present in the page. We can also print the link text of each Web link.
Please follow the steps mentioned below.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch elements with tag //a in the entire page, store it in a List.
4. Get the count of Links present in the Page.
5. Loop through the links and print the Attributes


List allLinks= driver.findElements(By.xpath("//a"));
//display the count of links in the page
System.out.println(allLinks.size());
//display the text for each link on the page
for (int i=0; i<allLinks.size(); i++)
{
        //display href for each link
 System.out.println(allLinks.get(i).getAttribute("href"));
 //display text for each link
 System.out.println(allLinks.get(i).getText());
 //perform click action
 allLinks.get(i).click();

}
16. Other Browser (Internet Explorer)

Using Internet Explorer with Web Driver.

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

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

WebDriver driver =new InternetExplorerDriver();
driver.get("www.google.com");

17. Other Browser (Chrome)

Using Chrome with Web Driver.

Please follow the steps mentioned below.

1. Set System Property for the Driver and give path of the Chrome Driver.
2. Create a Web Driver Object.
3. Open an URL

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

WebDriver driver = new ChromeDriver();
driver.get("www.google.com");

18. PROXY settings.
Please follow the steps mentioned below.

1. Import Selenium.Proxy
2. Create a Profile object for Firefox
3. Create a string variable with value.
4. Create a Proxy object.
5. Set the values through proxy.
6. Set the proxy preference to proxy object using profile object.
7. Pass the profile object to Firefox Driver.
import org.openqa.Selenium.Proxy

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

19. File Download

Please follow the steps mentioned below.

1. Create a PROFILE object of Browser.
2. Set Preference, by giving Download Destination Directory.
3. Set Preference, by giving Default Folder. 0 => Desktop, 1=>System Default Location, 2 => Indicates a custom Folder Location
4. Set Preference, a comma-separated list of MIME types to save to disk without asking what to use to open the file. Default value is an empty string.

After coding the above mentioned steps, now start the driver and click on Download button/link.
1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Fetch the Download web element and click.
FirefoxProfile Prof = new FirefoxProfile();
Prof.setPreference("browser.download.dir", "D:\\java prj");
Prof.setPreference("browser.download.folderList", 2);
Prof.setPreference("browser.helperApps.neverAsk.saveToDisk","application/zip");
 
WebDriver driver = new FirefoxDriver(Prof);
driver.get("http://seleniumhq.org/download/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);
driver.findElement(By.xpath("//a[@name='client-drivers']/table/tbody/tr[1]/td[4]/a")).click();

20. File Upload

Please follow the steps mentioned below.

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. Store the Source path of file in a variable.
4. Fetch the Upload web element text box and give path using variable.
5. Fetch the upload button and click

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

21. Handling JAVA ALERT

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

1. Create Driver for any Browser(Mozilla).
2. Go to the URL.
3. You get an alert asking to click on 'YES' or 'NO' button.
4. First Confirm if it is JAVA alert window.
5. Write a code to switch the control to Alert window.
6. In the Alert window, either ACCEPT by clicking on 'YES'
    or CANCEL by clicking on 'NO'.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.2shared.com/");
driver.manage().timeouts().implicitlyWait(3,TimeUnit.MINUTES);

Alert alert = driver.switchTo().alert();
alert.accept();
//or
alert.dismiss();

For more information about list of courses visit Software Testing Training Institute in India





















Comments

Post a Comment

Popular posts from this blog

BEST AUTOMATION TESTING TOOLS FOR 2018 (TOP 10 REVIEWS)

10 Remarkable Learning Quotes From 10 Astonishing People