Selenium and Java Interview Questions
1. What are the challenges with selenium automation?
Selenium support only for the thing which is render on browser. There is no support for
non-web automation like desktop or stand-alone application. Like if we want to scan
pdf (need Apache PDFBox JAR files to read PDF content on a browser using Selenium
Web-driver) or file upload or to read barcode(ZXing(“zebra crossing”))/captcha(Sikuli
for image based testing for Image Testing) selenium cant support. For that we need to
integrate Selenium with some external utilities and that is challenge. It cannot automate
audio and video. i.e. In many scenarios selenium rely on third party tool like image,
reporting etc.
Timeout/Sync issues(cypress). No intelligence to understand browser behaviour that
due to traffic its taking time to download.
Test execution is slow in Internet Explorer.
Limited reporting. No in-built reporting capabilities: To generate summary and
detailed report of test execution, selenium will use third party tool like TestNG, Junit
etc.
We can’t automate ad-hoc test cases.
No technical support: Since Selenium is open source software, you have to rely on
community forums to get your technical issues resolved.
New features may not work properly
Selenium does not provide any test tool integration for Test Management.
We should know at least one of the supported programming languages to create tests
scripts i.e. Selenium, doesn’t allow for codeless testing.
2. What are new selenium4 features?
WebDriver API Became W3C Standardized.
Improved Grid
A Better UI
Can take screenshot at element level, section level and page level.
Support for relative locators: left, right, top, bottom
3. Difference between [Link] and [Link]?
In [Link] search will done on entire page that is page.
Where in [Link] search will done on element level i.e. first it
generate WebElement and then search will done on the given WebElement.
4. Difference between Page Object Model and Page Factory?
This two are design pattern used to store WebElements as object repository.
Page Object Model(POM) is a selenium design pattern like a repository where we store
all the WebElements. This has become very popular this days, because it is very easy
to manage, make code reusable by eliminating duplication of codes. Its benefits is that
if UI changes in the future we can update WebElements to page classes in POM or
object repository.
Syntax: By login=[Link]("proceed");
public WebElement signIn()
{ return [Link](login); }
Page factory is an API follow same principle of keeping repository objects or page
classes separate from test classes just instead of By we use @FindBy to find elements
and to initialize WebElements using initElements process.
i.e. A Factory class is used to make using Page Objects simpler and easier. First, we
need to find the web elements by annotation@FindBy in page classes. Then initialize
the elements using initElements() when instantiating the page class.
Syntax: @FindBy(name="proceed") private WebElement login;
public WebElement signIn()
{ return login; }
#1)@FindBy: @FindBy annotation is used in PageFactory to locate and declare the
web elements using different locators. Here, we pass the attribute as well as its value
used for locating the web element to the @FindBy annotation and then the WebElement
is declared.
2) initElements(): The initElements is a static method of PageFactory class which is
used to initialize all the web elements located by @FindBy annotation. Thus,
instantiating the Page classes easily. initElements(WebDriver driver, [Link]
pageObjectClass)
5. What are the different locators supported by selenium?
Id
name
className
cssSelector
xpath
linkText
tagName
partialLinkText
6. How to overcome StaleElementReferenceException in Selenium?
Stale means outdated. When you identify any element and move out of the page and
came back and try to use that founded element will get
StaleElementReferenceException as element will get disappear when you move out of
the page.
So in that case again if you want to use that element then grab that element again one
more time when you landed back onto the page.
7. Difference between xpath and css?
CSS is faster than xpath.
Xpath can use both forward and backward directions that you can navigate from
parent to child or child to parent using xpath whereas css can only move forward.
CSS does not allow text.
//<knownXpath>/parent::* or
//<knownXpath>/parent::elementName
//<knownXpath>/..
//<xpathOfContextElement>/child::<elementName> or
//<xpathOfContextElement>/child::*
//<xpathOfContextElement>/<elementName>
8. How to access nth element using CSS selector?
Syntax: <type>:nth-child(n)
Ex: tr:nth-child(7)
9. How to handles alerts in selenium WebDriver?
Java script alert are those whose html code is not present. Alert is a small
message box which displays on-screen notification to give the user some kind of
information or ask for permission to perform certain kind of operation. It may be also
used for warning purpose. Here are few alert types:
1) Simple Alert: This simple alert displays some information or warning on the screen.
2) Prompt Alert: This Prompt Alert asks some input from the user and selenium
webdriver can enter the text using sendkeys(" input…. ").
3) Confirmation Alert: This confirmation alert asks permission to do some type of
operation. Like cancel or ok.
Syntax: [Link](); //used to switch on alert
[Link]().alert().getText(); //to get text of alert
[Link]().alert().accept(); //to accept alert
[Link]().alert().dismiss(); //to decline alert
[Link]().alert().sendKeys(keysToSend); //to send text on alert
10. What are different exceptions you faced in Selenium WebDriver?
WebDriverException: if don’t invoke browser properly or This Exception occurs
when the driver is performing the action after immediately closing the browser.
NoSuchElementException: This exception occurs when WebDriver is unable to
identify the elements during run time. Due to wrong selector or selector, which is, not
exist.
NoSuchFrameException: This Exception occurs when the driver is switching to an
invalid frame, which is not available.
NoAlertPresentException: This Exception occurs when the driver is switching to an
invalid Alert, which is not available.
NoSuchWindowException: This Exception occurs when the driver is switching to an
invalid Window, which is not available.
ElementNotVisibleException: This Exception occurs when the element presence is
in DOM, it is not visible.
ElementNotInteractableException: if element is hidden by some other element
SessionNotCreatedException: when browser is not invoked
TimeOutException: when got synchronization issues with wait
invalidselector: if proper selector not provided for locating WebElement
illegaleStateException: The root cause of [Link] is we have
not specified the path of the driver properly in the system property.
StaleElementReferenceException: This Exception occurs when the Element belongs
to a different frame than the current one. The user has navigated away to another page
and because of which element get disappear
11. What is framework? What are different types of framework available?
Framework is a set of rules and best practices for a systematic resolution of problem.
There are different types of automation frameworks:
Data-Driven
Keyword-driven
hybrid/imp
behavioural-driven/BDD cucumber/imp.
12. How to run tests in headless mode.
Add arguments “--headless” in specific browser options like for chrome.
Create class of browserOptions: ChromeOptions co=new ChromeOptions();
Add headless in it: [Link](“--headless”);
pass that object to driver: WebDriver driver=new ChromeDriver(co);
13. How to handle window-based alerts/pop-ups in selenium?
Selenium only supports web-based applications does not support windows-based
application however following approaches can help:
Use Robot class java-based utility to simulate the keyboard and mouse actions to
handle window-based pop-ups.
Robot rb =new Robot();
[Link](KeyEvent.VK_ENTER);
[Link](KeyEvent.VK_ENTER);
Autolt integration with Selenium help to automate Window-based pop-ups.
14. What are listeners in selenium?
Listeners is an interface that modifies the behaviour of the system. Listeners allows
customization of reports and logs.
Listeners mainly comprise of two types:
1. WebDriver Listeners
2. TestNG Listeners
WebDriver listeners, "Logging" happens before/after event occurrence such as
click/SendKeys etc. But in case of TestNG, there are the actual "listeners" which listen
(here the method gets called automatically) to the test execution events. A few examples
are: onStart(), beforeStart(), afterFinish(), and onFinish() etc. That's why TestNG
listener is preferable.
15. Difference between String Buffer and String Builder?
StringBuffer is synchronized i.e. Thread safe. It means two threads cant call methods
of StringBuffer simultaneously.
StringBuilder is not synchronized i.e. not thread safe. It means two threads can call
the methods of StringBuilder simultaneously.
If you think multiple test which access it at a time can damage or modify string then
use StringBuffer. If your test framework environment will go in parallel mode better
to use StringBuffer.
If you are in a single-threaded environment or don’t care about thread safety, you
should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.
StringBuilder is faster than StringBuffer.
StringBuffer and StringBuilder classes provide methods to manipulate strings.
16. What are the advantages of selenium in automation testing world?
It is open source automation testing tool.
It is exclusively used for web based application it means its support only that
application which is render on browser.
Support for multiple browser by keeping same code by changing only browser name
like Chrome, Firefox, Internet Explorer, Safari etc.
Selenium works with multiple platform like windows, Linux etc.
Selenium can be coded in multiple language like python, java, php, javascript etc.
Selenium easily integrated with Agile, DevOps, Continuous Delivery workflow
Supports mobile testing just you need additional software like appium or selendroid
which are based on selenium.
Large library for plug-ins: Selenium can be extended beyond its standard functionality
with a wide range of plug-ins for third party tool.
Selenium grid allows parallel execution.
17. What is the purpose of static methods and variables?
Static is a part of class not object;
When a variable is declared as static, then a single copy of variable is created and shared
among all objects at class level.
Static variables are, essentially, global variables. All instances of the class share the
same static variable.
When we want to refer common property to all the objects then we use static variable
e.g student name and roll no may be different but student's school name will be same
for all the students. Java static variable gets memory only once in class area(method
area) at the time of class loading. We can create static variables at class-level only.
Example:
package java_examples;
public class Demo extends Demo2 {
static int a=5; //should be declared at class level
public static void main(String[] args) {
static int a=5; //illegal modifier for parameter gives compile time error
Static block and static variables are executed in order they are present in a program.
Example:
class Test
{
// static variable
static int a = m1();
// static block
static {
[Link]("Inside static block");
}
// static method
static int m1() {
[Link]("from m1");
return 20;
}
// static method(main !!)
public static void main(String[] args)
{
[Link]("Value of a: "+a);
[Link]("from main");
}
}
Output:
from m1
Inside static block
Value of a: 20
from main
static method:
When a method is declared with static keyword, it is known as static method.
The most common example of a static method is main( ) method.
Use static methods for changing static variables.
Method declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way
Example:
// java program to demonstrate restriction on static methods
class Test
{
// static variable
static int a = 10;
// instance variable
int b = 20;
// static method
static void m1()
{
a = 20;
[Link]("from m1");
// Cannot make a static reference to the non-static field b
b = 10; // compilation error
// Cannot make a static reference to the
// non-static method m2() from the type Test
m2(); // compilation error
// Cannot use super in a static context
[Link](super.a); // compiler error
}
// instance method
void m2()
{
[Link]("from m2");
}
public static void main(String[] args)
{
// main method
}
}
18. Usage of this and super keyword in java?
this: belongs to local class variable
this is a keyword used to refer current local class variable or we can say used to
initialize class level variables in the constructors using local variables.
this keyword can only be used for constructors.
For example, in Page Object Model we use this keyword in page object
repository/page classes for initializing a WebDriver object.
public class RediffLogin {
WebDriver driver;
public RediffLogin(WebDriver driver) {
//[Link]=driver; normal page object pattern style
[Link](driver, this); //page object factory style
}
We can use more than one this keyword inside constructor at a time.
super: belongs to immediate parent class
We can use super keyword to access the data members or field of parent class (in
inheritance) if in case parent and child class have same field. super is used to refer
immediate parent class instance variable.
Program:
class Animal{ String color="white"; }
class Dog extends Animal{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output:
black
white
super keyword is also used to invoke parent class method.
Program:
class Animal
{ void eat(){[Link]("eating...");} }
class Dog extends Animal{
void eat(){ [Link]("eating bread..."); }
void bark(){ [Link]("barking..."); }
void work(){ [Link](); bark(); }
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output:
eating...
barking...
super is used to invoke parent class constructor.
Program:
class Animal{
Animal(){ [Link]("animal is created"); }
class Dog extends Animal{
Dog(){ super(); [Link]("dog is created"); }
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog(); }}
Output:
animal is created
dog is created"
19. Difference between Array and Array List?
Sr. No. Array ArrayList
1 Array is static. ArrayList is dynamic.
Array is a fixed length data structure, we cannot ArrayList is a variable length Collection class, whic
2 change length of array once created grows dynamically.
We cannot store primitives in ArrayList, it can only
store objects, primitives are automatically converted
3 Array can contain both primitives and objects objects which is known as auto-boxing.
Array does not support to generic, means it
contains similar types of data called strong type ArrayList support generic means we can store all
4 collection datatype values in one ArrayList.
To get the size of array we have length()
5 attribute. To get the size of ArrayList we have attribute size()
we can iterate through array either by for-loop we can iterate through ArrayList either by iterator,
6 or for each loop. loop or for each loop.
20. Difference between abstract class and interface?
Abstraction is hiding the internal implementation of the feature and only showing the
functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract
class and interface are used for abstraction. Ex of Interface: ITestListner inteface
1) Fields/Variables:
Interface fields are public, static and final by default. Interfaces still don’t support non-static
and non-final variables. Interfaces can only have public, static and final variables. On the other
hand, abstract class can have static as well as non-static and final as well as non-final variables.
They also support private and protected variables along with public variables.
2) Methods:
Interface contains abstract methods. However, from Java 8, interface can have default
method(used to set some default functionality to the interface) and static methods(to add utility
methods into the interface) and from Java 9, it can have private methods as well to share some
task between the non-abstract methods of the interface. Interfaces don’t support final methods.
But, abstract classes support final as well as non-final methods and static as well as non-static
methods along with abstract methods. Also note that, only interfaces can have default methods.
Abstract classes can’t have default methods.
3) Constructors
Interfaces can’t have constructors. Abstract classes can have any number of constructors.
4) Member’s Accessibility
All members of interfaces are public by default. Interfaces don’t support private and protected
members. But, abstract classes support all type of members – private, protected and public
members.
5) Multiple Inheritance
A class can extend only one abstract class, but can implement multiple interfaces. Thus, a class
can inherit multiple properties from multiple sources only through interfaces, not through
abstract classes.
21. Difference between HashMap and Hash table.
HashMap is not synchronized. It is not thread-safe and cant be shared between many
threads without proper synchronization code.
Hashtable is synchronized. It is thread-safe and can be shared with may threads.
HashMap allows one null key and multiple null values.
Hashtable does not allow any null key or null values.
22. Difference between final, finally and finalize.
23. Where should i use selenium grid?
Selenium grid is used to execute same or different test scripts on multiple platforms and
browsers concurrently so as to achieve distributed test execution and testing under different
environments to save execution time.
24. How many objects will be created in the following code?
String s1=”Welcome”;
String s2=”Welcome”;
String s3=”Welcome”;
Ans: only one object is created because String is immutable. Creating a string like this is
called string literal when you create a string literal jvm check string constant pool area first
and if it is present in pool, reference to pooled instance is returned and if it is not exists in the
pool then new instance is created and placed in the pool.
25. Difference between get and navigate method in Selenium?
As we know every URL loaded in browser will be in browser history and navigate allows to
access that to browser’s history, i.e. you can navigate back and forward as we do in a browser
manually by clicking back and forward button or navigate to a given URL and also provides
you to refresh the currently loaded page.
Whereas get() method is synonyms for to() method both methods do the same thing. They
load a new web page in the current browser window. This is done using an HTTP GET
operation, and the method will block until the load is complete. Internally to() method call
get() method.
Actually WebDriver has a nested static interface Navigation which has a method back(),
forword(), to(), refresh() which allows the selection of what to do next.
[Link]("[Link]
[Link]().to("[Link]
[Link]().forward();
[Link]().back();
[Link]().refresh();
26. Difference between quit and close methods in WebDriver?
close( ) WebDriver command 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/currently
active at that time. It wont close the remaining Browser windows.
Where as quit( ) WebDriver command is generally used to shut down the WebDrivers
instance. Hence it closes all the Browser windows that are opened by the Selenium
Automation.
close( ) and quit( ) work in the similar way when Selenium Automation opens only single
Browser window. They differ in their functionality when there are more than one Browser
windows opened by the Selenium Automation.
27. What is implicit wait?
In implicit wait we define wait time globally. i.e. whenever we perform any
operation and if its get failed because of no element found, so in that case before throwing
an exception it say webdriver to wait for some seconds and it will keep polling to the DOM
(Document Object Model) to get that element.
Time mentioned in implicit wait is the maximum time for which driver waits
i.e. its wait for element only till it get found and immediately resume the execution
after getting an element. Standard wait time: 5sec.
If the element is not available within the specified Time an
NoSuchElementException will be thrown.
Advantages: it is declared globally. i.e. it is applicable to all. No need to define for
each individual.
Pros: code readable
Cons: performance issue not caught
Syntax: [Link]().timeouts().implicitlywait(time, [Link]);
28. Difference between implicit and explicit wait?
The explicit wait is used to tell the Web Driver to wait for certain conditions
(Expected Conditions) or the maximum time exceeded before throwing an
"ElementNotVisibleException" exception.
The explicit wait is applied only for specified elements. Explicit wait gives better
options than that of an implicit wait as it will wait for dynamically loaded Ajax elements.
There can be instance when a particular element takes more than a minute to load.
In that case you definitely not like to set a huge time to Implicit wait, as if you do this your
browser will going to wait for the same time for every element. To avoid that situation you
can simply put a separate time on the required element only. By following this your
browser implicit wait time would be short for every element and it would be large for
specific element. In short use explicit wait in a scenario where at particular situation you
need more load time.
In explicit wait, it target one specific element only that means its not applied
globally.
Pros: no performance issue as it targetting to specific element
Cons: more code required.
Explicit wait is achieved in two ways: WebDriverWait and Fluent Wait.
WebDriverWait:
WebDriverWait find the element repeatedly until Time Out or till the object gets found. For
that it constantly keep an eye on DOM.
Syntax: WebDriverWait obj=new WebDriverWait(driverreference, time);
[Link]([Link](“Arguments”));
example:
WebDriver driver=new ChromeDriver();
WebDriverWait w=new WebDriverWait(driver,5);
[Link]([Link](element));
where, driverreference is to know on which i am playing this role and Time for how
much time i need to wait.
Scenario:
1. your card is accepted
2. your order is being processed
3. confirmation
And in that scenario if you have same html code for all three.
Cons: Code is little bit complex to write.
Fluent wait:
Fluent waits find the element repeatedly at regular intervals of time until Time Out or till
object gets found. It keep eye on DOM.
for example:
1. your card is accepted
2. your order is being processed
3. confirmation
And in that scenario if you have same html code for all three.
Cons: Code is little bit complex to write.
Syntax:
Wait<WebDriver> w = new
FluentWait<WebDriver>(driver).withTimeout([Link](30)).pollingEvery(
D [Link](3)).ignoring([Link]);
OR
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30,
[Link]).pollingEvery(5,
[Link]).ignoring([Link]);
//WebElement we = [Link](isTrue);
WebElement we = [Link](new Function<WebDriver,T>()
{ public returntype_of_result apply(WebDriver driver)
{ if(ExpectedConditionisTrue)
{ return result; }
else
{ return null; } } });
Implementations should wait until the condition evaluates to a value that is
neither null nor false. Because of this contract, the return type must not be Void. If the
condition does not become true within a certain time (as defined by the implementing
class), this method will throw NoSuchElementException.
Note: Function is a functional interface who have only one abstract method
apply.
Note: 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 their own specified
speeds. So the test scripts should be written in such a way that both these components will work
with same speed. This will help to avoid “Element Not Found” error. So when such two or
more components are involved to perform any action, synchronization help them to work
together with the same pace (speed in working). So we can say that the co-ordination between
these components to run parallel is called Synchronization. Synchronization can be achieved
in selenium WebDriver using wait.
29. In how many ways we can handle frames in the application using WebDriver
methods?
Frame is a component hosted on page. It is an HTML document that is included in
another HTML document just like a container which is used to place the contents from
another source. Eg: Advertisements, Youtube Videos etc. also called as “iframe”.
Switch to frame either by index, string or webElement. (i.e. With Frame ID, Frame
name or Frame webElement)
Syntax: [Link]().frame(arguments);
interview question:
Q. Where we use action class?
Ans: when we want to move mouse to a particular element/ui. i.e. keyboard & mouse
interaction
Actions a=new Actions();
right click means context click;str
drag & drop,double click,enter text in capital etc.
//[Link](drag).contextClick().build().perform();
// [Link](drag).build().perform();
// [Link]().build().perform();
Q. How to handle multiple window in selenium?
Ans. Using [Link]().window(id of window);
using [Link]() we will get the handles and ids of all opened window which
store it into one set.
Q. How to come to default window?
Ans: [Link]().defaultContent();
Q. how many frames are present in application.
Ans: using [Link]([Link](“iframe”));
using [Link]([Link](“frameset”));
30. Code to handle 3rd child window?
Ans: Ways to Handle Window in Selenium using tab:
Switch between two tabs using switchTo()
Switch between two tabs using sendKeys Actions
// This will return the number of windows opened by Webdriver and will return Set of Strings
ArrayList<String> tabs= new ArrayList<String> ([Link]());
[Link]().window([Link](1));
OR
Set<String> handles = [Link]();
Iterator<String> it = [Link]();
String parent = [Link]();
String child1 = [Link]();
String child2 = [Link]();
String child3 = [Link]();
[Link]().window(child3);
31. How to handle https certifications?
Ans: SSL (Secure Sockets Layer) is a standard security protocol for establishing a secure
connection between the server and the client which is a browser. It ensures secure
transformation of data across the server and client application using strong encryption
standard or digital signature. Now, if the browser is unable to establish a secured
connection with the requested certificate, then the browser will throw "Untrusted
Connection" exception ask the user to take appropriate action and for that Desired
Capabilities is used to configure the driver instance of Selenium Webdriver and to
handle untrusted SSL certificate issue.
// Create object of DesiredCapabilities class
DesiredCapabilities cap=[Link]();
//Set ACCEPT_SSL_CERTS variable to true
[Link](CapabilityType.ACCEPT_SSL_CERTS, true);
//Set the driver path
[Link]("[Link]","Chrome driver path");
// Open browser with capability
WebDriver driver=new ChromeDriver(cap);
32. Different type of locators present in webdriver?
Ans: ID, Xpath, CSS, ClassName, Name, Linktext, tagName
33. Write Syntax for xpath and css if id and tag are given?
Xpath = //tagName[@attribute=‘value’]
CSS = tagName[attribute=‘value’]
34. How to use Contains regular expression to xpath?
//tagname[contains(@attribute,’value’)] ex:
//tagName[contains(@id,’value’)]
35. How to use regular expression to CSS?
tagName[attribute*=‘value’] ex: tagname[id*=’value’]
36. What is the class available in selenium to handle drop downs?
If Without selecting an option in the ‘From’ drop down list will not able to select one
from the ‘To’ list, and will get empty field in ‘To’ list called dynamic dropdowns.
Example: [Link]. Without selecting a city in the ‘From’ drop down list if you try
to select one from the ‘To’ list, you will find it’s empty.
When dropdown is with select tag is called as static dropdowns.
Select s=new Select(Locator of dropdown);
[Link](index);
[Link](value);
[Link](text);
Static DropDown Example:
spicejet example for selecting 2 adults as passenger:
Open [Link]
click on passengers.
Select 2 adults.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Sample {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
// [Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
[Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
WebDriver driver =new ChromeDriver();
[Link]("[Link] //open spicejet
[Link]([Link]("paxinfo")).click();
WebElement adult=[Link]([Link]("ctl00_mainContent_ddl_Adult"));
Select s=new Select(adult);
[Link]("2");
}
}
AutoSuggestive DropDown Example:
Scenario:
1. Open makemytrip
2. enter first three letters of city in from field.
3. select first option from autosuggestion
4. enter first three letters of city in destination field.
5. select first option from autosuggestion
Program:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Sample {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
// [Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
[Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
WebDriver driver =new ChromeDriver();
[Link]("[Link] //open makemytrip
[Link](5000);
WebElement we = [Link]([Link]("fromCity"));
// [Link]([Link]("value"));
[Link]();
WebElement fct = [Link]([Link]("//input[contains(@class,'react-
autosuggest__input')]"));
[Link]("Mum");
[Link](Keys.ARROW_DOWN);
[Link]([Link]);
WebElement dct =
[Link]([Link]("//input[contains(@class,'react-autosuggest__input')]"));
[Link]("Ban");
[Link](Keys.ARROW_DOWN);
[Link]([Link]);
}
}
37. What is the method to check if checkbox is selected?
Ans: isSelected(). Note: To find a number of check box present in a page first we need to
identify a locator which common to all check boxes. In case of checkbox generally it is in the
//input tagname with the type=”checkbox”. Find it. Then use findElements() instead of
findElement() as we need to find multiple elements using the provided locator and then get the
count of no. Of identifed element using size() method.
Handling Checkbox and getting the size of them with Selenium
Scenario:
Open spicejet.
Maximize window.
Take any one checkbox and check all properties of checkbox.
whether it is visible.
whether it is enabled.
whether it is selected. (initially not)
then select that checkbox and check whether it is get selected.
And finally count the number of checkbox present in the page.
Note:
To find a number of check box present in a page first we need to identify a locator which
common to all check boxes. In case of checkbox generally it is in the //input tagname with the
type=”checkbox”. Find it.
Then use findElements() instead of findElement() as we need to find multiple elements
using the provided locator and then get the count of no. Of identifed element using size()
method.
Program:
import [Link];
import [Link];
import [Link];
import [Link];
public class Sample {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
// [Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
[Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
WebDriver driver =new ChromeDriver();
[Link]("[Link] //open spicejet
[Link]().window().maximize();
[Link](2000);
WebElement chk_box =
[Link]([Link]("ctl00_mainContent_chk_friendsandfamily"));
[Link](chk_box.isDisplayed());
[Link](chk_box.isEnabled());
[Link](chk_box.isSelected());
chk_box.click();
[Link](2000);
[Link](chk_box.isSelected());
[Link]("Total no. of check box present in a page is:
"+[Link]([Link]("//input[@type='checkbox']")).size());
Output:
true
true
false
true
Total no. of check box present in a page is: 6
38. How to validate if element is visible or hidden in webpages?
Ans: using isDisplayed();
39. How to get the count of similar objects list in the web page?
[Link]([Link](“common identification for all”)).size();
40. Importance of desired capabilites Mechanism?
The desired capability is a series of key/value pairs that stores the browser properties
like browsername, browser version, the path of the browser driver in the system, etc. to
determine the behaviour of the browser at run time.
41. How to enter the text in capslock?
Ans:
[Link]("YOURELEMENTLOCATOR").sendKeys([Link],
"text")
42. How to mouse over on the web element on page?
Actions a =new Actions(driver);
[Link](“”).build().perform(); //to move mouse
[Link](“”).click().keyDown([Link]).sendKeys("mobile");//ente
rtext incaps
[Link](“”).doubleClick().build().perform(); //to double click
[Link](“”).contextClick().build().perform(); // to right click on item
43. Methods to handle Java Alert?
Java script alert are those whose html code is not present. Alert is a small message
box which displays on-screen notification to give the user some kind of information
or ask for permission to perform certain kind of operation. It may be also used for
warning purpose. Here are few alert types:
1) Simple Alert: This simple alert displays some information or warning on the
screen.
2) Prompt Alert: This Prompt Alert asks some input from the user and selenium
webdriver can enter the text using sendkeys(" input…. ").
3) Confirmation Alert: This confirmation alert asks permission to do some type of
operation.
Syntax: [Link](); //used to switch on alert
[Link]().alert().getText(); //to get text of alert
[Link]().alert().accept(); //to accept alert
[Link]().alert().dismiss(); //to decline alert
[Link]().alert().sendKeys(keysToSend); //to send text on alert
Example:
import [Link];
public class Sample {
public static void main(String[] args) throws Exception {
[Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
WebDriver driver =new ChromeDriver();
[Link]("[Link]
[Link](2000);
[Link]().window().maximize(); //maximize window
[Link](2000);
[Link]([Link]("name")).sendKeys("nita");
[Link]([Link]("alertbtn")).click();
[Link]([Link]().alert().getText());
[Link](2000);
[Link]().alert().accept();
[Link](2000);
[Link]([Link]("name")).sendKeys("nita");
[Link]([Link]("confirmbtn")).click();
[Link]([Link]().alert().getText());
[Link](2000);
[Link]().alert().accept();
}
}
Output:
Hello nita, share this practice page and share your knowledge
Hello , Are you sure you want to confirm?
44. How to get links count in the page?
Ans: [Link]([Link](“a”).size();
45. How to validate if we are navigated to child window successfully?
Ans: By checking the title of child window
46. Difference between relative and absolute xpath?
Absolute Xpath: It uses Complete path from the Root Element to the desire element.
Relative Xpath: You can simply start by referencing the element you want and go from
there.
When we find a xpath of any specific element without depending upon its parent node
called realtive xpath. Relative xpath is navigating from root of the parent to any child
using //.
When we find a xpath of any specific element with the help of its parent node called
absolute xpath. Absolut xpath is navigating from root of the parent to its immediate
child using /.
Always Relative Xpaths are preferred as they are not the complete paths from the Root
element. (//html//body). Beacuse in future any of the webelement when
added/Removed then Absolute Xpath changes. So Always use Relative Xpaths in your
Automation.
47. Write down the sample xpath syntax to handle parent from child object?
Syntax: //tagName[@attribute=value]/parent::tag name
48. What driver is must to run tests in firefox driver?
Ans: [Link]("[Link]","D:\\[Link]");
49. What driver is must to run tests in Chrome driver?
Ans: [Link]("[Link]","D:\\[Link]");
50. Difference between findElement and findElements?
FindElement identifies first object which matches with provided locator on the screen with top
left scanning. FindElements gets all the objects which matched and takes into List.
51. List out any 2 methods available in explicit wait.
Ans: visibilityOfElementLocated, PresenceOfElementLocated.
52. How to take screenshots with selenium webdriver.
Ans: Steps to take screenshot in selenium:
To take Screenshot in selenium first we need to cast the driver object into the
TakesScreenshot interface using explicit casting. (i.e. Converting one data type into
another one.
Then call the method takeScreenShotAs using . Opeartor and by passing argument
[Link] whose return type is File. This will take and store Screenshot at default
memory location.
Now if you want to store it into a particular location then you can copy that file from
default location to a specified location using static method of FileHandler class. (Other
alternative is FileUtils, [Link](source,new file”dest”).)
Program:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Sample {
public static void main(String[] args) throws Exception {
[Link]("[Link]", "D:\\Users\\Pankaj
Shende\\Desktop\\NPS\\[Link]");
WebDriver driver =new ChromeDriver();
[Link]("[Link] //open spicejet
File source=((TakesScreenshot)driver).getScreenshotAs([Link]);
[Link](source);
File dest=new File("D:\\Users\\Pankaj Shende\\Desktop\\NPS\\[Link]");
[Link](source, dest);
}
}
53. How to hit enter from webdriver commands?
Ans: sendKeys(“[Link]”);
54. parameterization:
package inheritance;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Sample2{
public static void main(String[] args) throws EncryptedDocumentException, IOException,
InterruptedException {
FileInputStream file=new FileInputStream("D:\\Users\\Pankaj
Shende\\Desktop\\[Link]");
@SuppressWarnings("resource")
XSSFWorkbook workbook=new XSSFWorkbook(file);
XSSFSheet input = [Link]("Second Sheet");
for(Row row:input)
{
for(Cell cell:row)
{
//CellType cellType = [Link]();
switch([Link]())
{
case NUMERIC:
[Link]([Link]()+" ");
break;
case STRING:
[Link]([Link]()+" ");
break;
default:
[Link](" ");
break;
}
[Link](" ");
}
[Link]();
}
}
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Sample {
public static void main(String[] args) throws InterruptedException, IOException {
WebDriver driver;
DesiredCapabilities cap;
Properties prop = new Properties();
FileInputStream fis = new
FileInputStream([Link]("[Link]")+"\\[Link]");
[Link](fis);
String browser=[Link]("browser");
String path = [Link]("[Link]");
String url = [Link]("url");
[Link](path);
switch(browser)
{
case "chrome":
ChromeOptions c= new ChromeOptions();
[Link](CapabilityType.ACCEPT_SSL_CERTS,true);
[Link]("--disable-notifications");
[Link]("[Link]",path+"\\[Link]");
driver=new ChromeDriver(c);
break;
case "firefox":
cap=[Link]();
[Link](CapabilityType.ACCEPT_SSL_CERTS,true);
FirefoxOptions f=new FirefoxOptions();
[Link](cap);
[Link]("[Link]",path+"\\[Link]");
driver=new FirefoxDriver(f);
break;
default:
[Link]("[Link]",path+"\\[Link]");
driver=new InternetExplorerDriver();
break;
}
[Link](url);
}
}