Selenium Interview Questions Flashcards

1
Q

What is Selenium? Why do you prefer the Selenium Automation Tool? What are the testing types that can be supported by Selenium? Limitations of Selenium?

A

Selenium is a suite of software tools used to automate Web Browsers.

Prefer to Use Selenium Tool for the following:
● It is an Open source suite of tools mainly used for Functional and Regression Test Automation.
● Selenium supports various Operating environments:
MS Windows,Linux,Macintosh etc…
● Selenium supports various Browsers:
Mozilla Firefox,IE,Google Chrome,Safari,Opera etc…
● Selenium supports various programming environments to write programs (Test scripts):
Java,C#,Python,Perl,Ruby,PHP, JS

Scenarios we cannot automate using Selenium WebDriver:
● Automating Captcha is not possible
● We can not read barcode using Selenium WebDriver
● Windows based pop ups
● Image validation and comparison
● PDF validation and comparison

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Selenium IDE? What is Selenium RC? What is Selenium Grid? When do you use Selenium Grid? What are the advantages of Selenium Grid? Which version of Selenium Webdriver are you using?

A

Selenium IDE AKA Selenium Integrated Development Environment is a Firefox plugin.

Selenium RC AKA Selenium Remote control / Selenium 1.

Selenium WebDriver AKA Selenium 2 is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it.

Selenium Grid is a tool used to distribute your test execution on multiple platforms and environments concurrently.

Usage or Advantage of Selenium Grid:
● It allows running test cases in parallel thereby saving test execution time.
● It allows multi-browser testing
● It allows us to execute test cases on multi-platform

We are using the Selenium 3.0 because of compatibility issues which can support most of the latest browsers any way we are creating maven project any dependency we can easily update in pom.xml file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the types of WebDriver APIs available in Selenium? What is the super interface of WebDriver? What is a headless browser?

A
Different webdriver API:
● Gecko Driver
● InternetExplorer Driver
● Chrome Driver
● Safari Driver
● HTMLUnit Driver

The Super interface of WebDriver is SearchContext Interface.

HTMLUnitDriver, because it is headless browser which have less User Interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the Locators available in Selenium? Which locator do you prefer?

A

There are eight locators in selenium to identify the webelements on the webpage:
ID, ClassName, Name, TagName, LinkText, PartialLinkText, XPath, CSS Selector.

The preference of the locator depends on the project.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is an XPath? What is the difference between Absolute Path and Relative Path? What is the difference between “/” and “//”? In which situations are you going to use Xpath?

A

XPath is used to locate the elements. Using XPath, we could navigate through elements and attributes in an XML document to locate web elements.

● 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 and it is called Absolute XPath.

Example : /html/body/td/tr/div[1]/div[2]

● 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. And it is called Relative XPath.

Example: //input[@id=’username’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a complex xpath or css expression? Which one is better? What is the difference?

A

xpath:
“//label[@for=’personal_txtLicExpDate’]/following-sibling::img”

css:
“input[name^=’pass’]”

Both CSS and XPATH are great in Selenium Automation

When we want to automate the test Case on Internet Explorer sometimes CssSelector is better and for the rest (Browser i.e. Firefox, Chrome and Safari) xpath is better

Difference between both Xpath and CSS:

● Generally CSS is easy to use and readable over XPATH.
● CSS works only in forward direction while with xpath, we can search elements backward or forward
● Xpath can work with text while CSS cannot

Speed wise CSS and XPATH can be equal, or either one would be a bit speedier than the other. Therefore speed comparison can be ignored. However, off the record, I have encountered that CSS is much faster than XPATH in IE Browser.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to launch a browser using Selenium WebDriver? Explain the line of code

A
// set the property for the driver, specify its location via the webdriver.chrome.driver
System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
// instantiate an instance of ChromeDriver, which will be driving our browser:
public static WebDriver driver = new ChromeDriver();
// navigate to the specific url
driver.get("http://google.com");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the alternative to driver.get() method to open a URL using Selenium WebDriver? What is the difference?

A

driver.navigate().to(“http://www.example.com”);

The navigate interface also exposes the ability to move backwards and forwards in our browser’s history:

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the difference between driver.close() and driver.quit() methods?

A

close() - It is used to close the browser or page currently which is in focus.

quit() - It is used to shut down the webdriver instance or destroy the web driver
instance (close all the windows).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to get the text of a web element? How to get an attribute value using Selenium WebDriver?

A

String buttonText = driver.findElement(By.cssSelector(“div.success”)).getText();

String innerText = driver.findElement(By.cssSelector(“div.success”)).getAttribute(“type”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between driver.findElement() and driver.findElements() commands? What is the return type of findElements?

A

findElement() will return only a single WebElement and if that element is not located or we use some wrong selector then it will throw NoSuchElementexception.

findElements() will return List of WebElements – It returns an empty list, when
element is not found on the current page as per the given element locator mechanism. It doesn’t throws NoSuchElementException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you work with radio buttons which do not have an id attribute?

A

We can use click() ,if “id” is not present we can use xpath (i.e you can use relative or absolute), CSS or other locator type.

Also when there is a group of Radio Buttons/Check Boxes on the page then, it is possible that their names are the same, but values are different. In that case we can use the Webdriver findElements command to get the list of web elements and then loop through them.

List radioBtn=driver.findElements(By.name(“sex”));
for(WebElement radio: radioBtn) {
String value=radio.getAttribute(“value”);
if(radio.isEnabled() && value.equals(“Female”)) {
radio.click();
break;
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to select a value in a dropdown? How to check the multiple selected value in a dropdown?

A

We can use Select class

Select dropdown = new Select(driver.findElement(By.id(“designation”)));

● dropdown.selectByVisibleText(“Value”);
● dropdown.selectByIndex(1);
● dropdown.selectByValue(“value”);

isMultiple() Method

isMultiple() method is useful to verify if the targeted select box is multiple select box or not means we can select multiple options from that select box or not. It will return boolean (true or false) value. We can use it with if condition before working with select box.

Select listbox = new Select(driver.findElement(By.xpath(“//select[@id=’FromLB’]”)));

if (blistbox.isMultiple()){
listbox.selectByVisibleText(“Value”);
listbox.selectByVisibleText(“Value”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you handle an element in different windows? Getwindowhandle vs Getwindowhandles and the return types. Write a method to switch to the window based on title?

A

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. When we open the browser window and then 3 tabs pop open, selenium is focused on the first window.

getWindowHandle() will get the handle of the page the webDriver is currently controlling. Everytime Selenium opens a browser, it’s going to give an index ID for the page called handle. This handle is a unique identifier for the web page. This is different every time you open a page even if it is the same URL.

String handle= driver.getWindowHandle();

getWindowHandles() method or commands returns all handles from all opened browsers by Selenium WebDriver during execution

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

You can use SwitchTo().Window(“handle”) to switch to the window you desire.

You can use SwitchTo().Window(“mywindowID”), if you know the window ID.

SwitchTo().Window(“”) will always go back to the base/main window.

Method to switch to window based on title

public switchToWindow(String titleName) {
driver.switchTo().window("titleName"); //titleName =windowName
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How would you handle elements that are in a different frame? How to identify the frame which does not have Id as well as name?

A

Using switch commands we can switch to different frame to handle elements:

We can switch to the frame 3 different ways:

  1. Switch to Frame by Name or ID
    driver. switchTo().frame(“iframe1”)
  2. Switch to Frame by WebElement
    WebElement iframeElement = driver.findElement(By.id(“IF1”));
    driver.switchTo().frame(iframeElement);
  3. Switch to Frames by Index
    driver. switchTo().frame(0)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can we handle web based pop-up? How can you handle JavaScript Alerts? Can we inspect an alert? How many ways can you handle alerts? How do you get text from alert? How do you send text to alert? How can we handle windows based pop up?

A

We can handle web based pop-ups using Alert Interface.

There are four methods that we would be using along with the Alert interface.

Alert alert = driver.switchTo().alert(); or driver.switchTo().alert()

1) void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
alert. dismiss(); or driver.switchTo().alert().dismiss();

2) void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
alert. accept(); or driver.switchTo().alert().accept();

3) String getText() – The getText() method returns the text displayed on the alert box.
alert. getText(); or driver.switchTo().alert().getText();

4) void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
alert. sendkeys(“text”); or driver.switchTo().alert().sendkeys(“text”);

Selenium WebDriver cannot handle window based pop ups, for that we can use Robot Class or third-party tools like AutoIT.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are the types of waits available in Selenium WebDriver? What is Implicit/Explicit/ Fluent Wait In Selenium WebDriver? What is WebDriverWait In Selenium WebDriver?

A

Implicit Wait
The implicit wait will tell the web driver to wait for a certain amount of time before it throws a “No Such Element Exception”. The default setting is 0. Once we set the time, the webdriver will wait for that time before throwing an “TimeOutException” exception.

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

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 an intelligent kind of wait, but it can be applied only for specified elements.

WebDriverWait wait=new WebDriverWait(drv,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("ckdmc"));

Fluent Wait
The fluent wait is used to tell the webdriver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an “ElementNotVisibleException” exception. Frequency: Setting up a repeat cycle with the time frame to verify/check the condition at the regular interval of time.

Consider a scenario where an element is loaded at different intervals of time. The element might load within 10 seconds, 20 seconds or even more than that if we declare an explicit wait of 20 seconds. It will wait till the specified time before throwing an exception. In such scenarios, the fluentwait is the ideal wait to use as this will try to find the element at
different frequencies until it finds it or the final timer runs out.

Wait wait = new FluentWait(WebDriver reference)

wait. withTimeout(Duration.ofSeconds(30));
wait. pollingEvery(Duration.ofSeconds(1));
wait. ignoring(NoSuchElementException.class);

18
Q

How to pause a test execution for 5 seconds at a specific point?

A

Thread.sleep(5000);

19
Q

How To Perform Right Click in Selenium WebDriver? Double Click? Hover over on a web element? Drag And Drop? What operations can you do using Actions class?

A

Using action class we can perform all of these operations

Actions action = new Actions(driver);
WebElement element=driver.findElement(By.linkText("TEST"));
//Double click
action.doubleClick(element).perform();
//Mouse over
action.moveToElement(element).perform();
//Right Click
action.contextClick(element).perform();
//Drag and Drop
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
action.dragAndDrop(element, target).perform();

We can perform following operation using action class:
● click (): Simply click on element
● doubleClick (): Double clicks on Element
● contextClick() : Perform a context-click (right click) on an element
● clickAndHold(): Clicks at the present mouse location (without releasing)
● dragAndDrop(source, target): Invokes click-and-hold at the source location and moves to the location of the target element before releasing the mouse. source – element to grab, target – element to release

20
Q

How to handle hidden elements in Selenium WebDriver? Is there a way to click hidden LINK in WebDriver?

A

First store that element in object, let’s say element and then write the following code to click on that hidden element

WebElement element=”property of element”;
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“arguments[0].click();”, element);

21
Q

How to input text in the text box using Selenium WebDriver? How to input text in the text box without calling the sendKeys()?

A

we can input text using sendkeys

WebElement email = driver.findElement(By.id(“email”));
email.sendKeys(“your@email.here”);

as well as

JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript(“document.getElementById(“email”).value=’your@email.here’;);

22
Q

How To Scroll Web Page Down Or Up Using Selenium WebDriver?

A

We use JavascriptExecutor

//to perform Scroll Up on application using Selenium
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,250)");
//to perform Scroll Down on application using Selenium
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0, -400)");
//to scroll an application to specified elements
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("arguments[0].scrollIntoView(true);",element);
23
Q

How to press the ENTER key on a text box In Selenium WebDriver? How to press the TAB key in Selenium?

A

driver. findElement(By.id(“Value”)).sendKeys(Keys.RETURN); or
driver. findElement(By.id(“Value”)).sendKeys(Keys.ENTER); or
driver. findElement(By.id(“Value”)).sendKeys(Keys.TAB);

24
Q

How do you handle the calendar elements? WebTables?

A

Step 1- Click on calendar
Step 2- Get all td of tables using findElements method
Step 3- using for loop get text of all elements
Step 4- using if else condition we will check specific date
Step 5- If the date is matched then click and break the loop.

public class CalendarHandling {
public static void main(String[] args) {
System.setProperty(“webdriver.firefox.marionette”,”G:\Selenium\Firefoxdriver\geckodriver.exe”);
WebDriver driver=new FirefoxDriver();
driver.get(“URL)
driver.findElement(By.id(“datepicker”)).click();
List
allDates=driver.findElements(By.xpath(“//table[@class=’ui-datepicker-calendar’]/tbody/tr/td”));

for(WebElement ele:allDates) {
String date=ele.getText();
if (date.equalsIgnoreCase("28")) {
ele.click();
break;
}
}
}

WebTable

List row
=driver.findElements(By.xpath("//table[@id='resultTable']/tbody/tr"));
for (int i = 1; i <=rows.size(); i++) {
String rowData = rows.get(i).getText();
if (rowData.contains(ID)) {
driver.findElement(By.xpath("//table[@id='resultTable']/tbody/tr["+i +"]/td[1]/input")).click();
break;
}
}
25
Q

How to capture Screenshot in Selenium WebDriver?

A

We use TakeScreenShot interface to capture screenshot

//Step 1. Convert web driver object to TakeScreenshot
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
//Step 2. Call getScreenshotAs method to create image file
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
//Step 3. Move image file to new destination
File DestFile=new File(fileWithPath);
//Step 4. Copy file at destination
FileUtils.copyFile(SrcFile, DestFile);
26
Q

What are the different exceptions you have faced in Selenium WebDriver? What is StaleElementReferenceException? Have you encountered it ever and how you handled it?

A

● ElementNotVisibleException
● NoSuchElementException
● NoSuchFrameException
● NoAlertPresentException
● NoSuchWindowException
● StaleElementReferenceException - One of the worst exceptions for an
automation engineer. WebDriver throws this exception when the element is
in the DOM and even visible on the screen but you can’t access the element
as a DOM reference change or element is no longer attached to the DOM.

Solution:

  1. We could refresh the page and try again for the same element.
  2. Wait for the element till it gets available
    wait. until(ExpectedConditions.presenceOfElementLocated(By.id(“table”)));
27
Q

How can you find Broken Links/Images in a page using Selenium WebDriver?

A

Broken links are links or URLs that are not reachable. They may be down or not functioning due to some server error. To find broken links using selenium it means we need to check the link which is pointing to the wrong URL or invalid URL.

A URL will always have a status with 2xx which is valid. There are different HTTP status codes which are having different purposes. For an invalid request, HTTP status is 4xx and 5xx.

Some of the HTTP status codes:
200 – Valid Link
404 – Link not found
400 – Bad request
401 – Unauthorized
500 – Internal Error

While doing validation you only have to verify status
200-Success- ok

Step to find broken links:
● Collect all the links from the webpage. All the links are associated with the Tag ‘a‘.
● Create a list of type WebElement to store all the Link elements in it.
● Now Create a Connection using URL object( i.e ., link)
● Connect using the Connect Method.
● Use getResponseCode () to get response code. eg 200

//There is character limitation so i couldn't paste the whole answer here. Please refer selenium pdf
List links = driver.findElements(By.tagName("a"));
for (int i=0; i
28
Q

Is it possible to automate the captcha using Selenium? List some scenarios which we cannot automate using Selenium WebDriver?

A

No we can’t automate captcha.

Less Support for Image based Testing, No Other Tool integration for Test management

29
Q

Have you done any cross browser testing within your Project?

A

Yes I have done cross browser testing in my framework using 3 browser initializations. Chrome, IE and Firefox testing using Webdriver. In our property file we store keys for the browser and everytime we change the value of the key execution will be happening on different browsers.

30
Q

How to Upload a file in Selenium WebDriver? How to Download a file in Selenium WebDriver?

A

sendKeys() method on the file-select input field to enter the path to the file to be uploaded …

WebElement uploadElement = driver.findElement(By.id(“uploadfile_0”));

// enter the file path onto the file-selection input field
uploadElement.sendKeys("C:\\newhtml.html");

To upload or download files in Selenium we can use Robot Class or get help from AutoIT or Sikuli

AutoIt is just another automation tool like Selenium but unlike Selenium it is used for Desktop Automation rather Web Automation. Robot Class is a Java based class that can simulate keyboard events in Selenium.

31
Q

What are the open-source Frameworks supported by Selenium WebDriver?

A

● JUnit
● TestNG
● Cucumber
● JBehave

32
Q

How To Login Into Any Site If It Is Showing Any Authentication Pop-Up for a Username And Password?

A

To do this we pass username and password with the URL

http: //username:password@url
e. g. http://myUserName:myPassword@gmail.com

Testing URL: http://abcdatabase.com/basicauth
Code: driver.get(“http://test:test@abcdatabase.com/basicauth”);

33
Q

What is the page object model ? What are the advantages of Page Object Model?

A

Page Object Model is a design pattern which has become popular in test automation for enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your AUT-Application Under Test.

The tests then use the methods of this page object class whenever they need to interact with the UI of that page, the benefit is that if the UI changes for the page, the tests themselves don’t need to be changed, only the code within the page object needs to change.

Advantages of Page Object Model:
● Code reusability – We could achieve code reusability by writing the code once and use it in different tests.
● Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.
● Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as members. The class will then implement the interface.
● Readability – Improves readability due to clean separation between test code and page specific code.

34
Q

What is the difference between POM and PageFactory?

A

A Page Object Model is a test design pattern which says organize page objects as per pages in such a way that scripts and page objects can be differentiated easily. A Page Factory is one way of implementing Page Object Model which is inbuilt in selenium.

In plain POM, you define locators using ‘By’ while in Page Factory, you use @FindBy annotation to define page objects.

Page Object Model is a design approach while PageFactory is a class which provides implementation of Page Object Model design approach.

In the plain page object model, you need to initialize every page object individually otherwise you will encounter NullPointerException while In PageFactory all page objects are initialized (Lazily) by using initElements() method.

Example from our framework:
@FindBy(name=”txtPassword”)
public WebElement password;

public LoginPageElements() {
PageFactory.initElements(BaseClass.driver, this);
}
35
Q

Suppose the developer changed the existing image to a new image with the same xpath. Does the test case pass or fail?

A

No test case will pass because we can not check the image using selenium.

36
Q

Scenario: you have 2 frames on the page and in 1 you need to enter some text in second you need to click a button. How can you do that? Can you switch from frame to frame directly?

A

I will first switch frame 1
driver.switchTo().frame(1);

and enter text then come to default main using driver.switchTo().defaultContent();

again I will switch to second frame
driver.switchTo().frame(2);

and click on button

37
Q

Scenario: there is a submit button on the page it has id property. By using id we got an element not found exception, how will you handle this situation? What might be the problem in this case?

A

We can use xpath or check that button or check if the button is inside the frame or we can use submit() rather than click() or else we can use the javaScriptExecutor for that.

Or maybe it takes some extra time for the button to get loaded in DOM. So we can add Explicit wait until the element becomes clickable.

38
Q

Write a dynamic XPath to locate a table’s 2nd row 3rd column data.

A

//to get 2nd row 3rd column data
WebElement cellIneed =
tableRow.findElement(By.xpath(“//table/tbody/tr[2]/td[3]”));

39
Q

Let’s say I have a page and on that page, there is a web table that has 4 columns and twenty rows. And I have to validate data in the last rows?

A

Use xpath index concept and take text of last row and do assertion

String url=”https://www.toolsqa.com/automation-practice-table/”;
driver.get(url);

//get number of rows
List rows = driver.findElements(By.xpath("//table[@summary='Sample Table']/tbody/tr"));

int lastRow = rows.size();
WebElement lastRow = driver.findElement(By.xpath(“//table[@summary=’Sample Table’]/tbody/tr[“+lastRow+”]”));

System.out.println(lastRow.getText());

OR:
List rows =
driver.findElements(By.xpath("//table[@summary='Sample Table']/tbody/tr"));
for (int i=rows.size()-1; i>=0; i--) {
String latRowValue=rows.get(i).getText();
System.out.println(latRowValue);
break;
}
40
Q

what is DOM? what can you see there?

A

The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.