Selenium WebDriver Interview Questions and Answers for Experience SET – 2
How to check the checkbox or radio button is selected ?
- Use isSelected() method to identify.
- The return type of the method is boolean.
- So if it return true then button is selected else not enabled.
1 | driver.findElement(By.xpath(“xpath of button”)).isSelected(); |
How do u get the width of the textbox ?
1 2 3 | driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getWidth(); driver.findElement(By.xpath(“xpath of textbox ”)).getSize().getHeight(); |
How to hover the mouse on an element ?
1 2 3 4 5 | Actions act = new Actions(driver); //webelement on which you want to move cursor act.moveToElement(webelement); |
Selenium WebDriver Interview Questions and Answers for Experience
While explaining the framework, what are points which should be covered?
a) What is the frame work?
b) Which frame work you are using.
c) Why This Frame work.
d) Architecture.
e) Explanation of every component of frame work.
f) Process followed in frame work.
g) How & when u execute the frame work.
h) Code (You must write code and explain).
i) Result and reporting.
j) You should be able to explain it for 20 Minutes.
What is the use of AutoIt tool?
- Some times while doing testing with selenium, we get stuck by some interruptions like a window based pop up.
- But selenium fails to handle this as it has support for only web based application.
- To overcome this problem we need to use AutoIT along with selenium script.
- AutoIT is a third party tool to handle window based applications.
- The scripting language used is in VBScript.
How to perform double click using WebDriver?
1 2 3 4 5 | Use doubleClick() method. Actions act = new Actions(driver); act.doubleClick(webelement); |
How to press Shift + Tab?
1 2 3 | String press = Keys.chord(Keys.SHIFT,Keys.ENTER); webelement.sendKeys(press); |
What is the use of contextClick() ?
- It is used to right click.
What is the difference b/w getWindowHandles() and getWindowHandle() ?
- getWindowHandles()- is used to get the address of all the open browser and its return type is Iterator<String>.
- getWindowHandle()- is used to get the address of the current browser where the control is and return type is String.
What are different components of your framework ?
- Library- Assertion, ConfigLibrary, GenericLibrary, ProjectSpecificLibrary, Modules.
- Drivers folder, Jars folder, excel file.
Selenium WebDriver Interview Questions and Answers for Experience
How to check all checkboxes in a page?
1 2 3 4 5 6 7 | List<webElement> chkBox = driver.findElements(By.xpath(“//htmltag[@attbute='checkbox']”)); for(int i=0; i<=chkBox.size(); i++){ chkBox.get(i).click(); } |
Selenium WebDriver Interview Questions and Answers for Experience
Count the number of links in a page.
- Use the locator By.tagName and find the elements for the tag //a then use loop to count the number of elements found.
1 2 3 4 5 | List<webElement> link = driver.findElements(By.tagName(“a”)); // this will print the number of links in a page. System.out.println(link.size()); |
What is the difference between implicit wait and explicit wait in selenium webdriver?
- There are two waiting methods, implicit wait and explicit wait
Implicit wait:
- When an implicit wait is implemented in tests, if WebDriver cannot find an element in the Document Object Model (DOM), it will wait for a defined amount of time for the element to appear in the DOM. In other terms, an implicit wait polls the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available.
- Implicit waits can slow down your tests, because once set, the implicit wait is set for the life of the WebDriver object’s instance. This means that when an application responds normally, it will still wait for each element to appear in the DOM which increases the overall execution time.
- Another downside is if for example you set the waiting limit to be 5 seconds and the elements appears in the DOM in 6 seconds, your tests will fail because you told it to wait a maximum of 5 seconds.
An example of an implicit wait is:
1 | driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); |
Explicit wait:
- Explicit waits are better than implicit wait. Unlike an implicit wait, you can write custom code or conditions for wait before proceeding further in the code.
- An explicit wait can be used where synchronization is needed, for example, the page is loaded but we are still waiting for a call to complete and an element to appear.
- Selenium WebDriver provides WebDriverWait and ExpectedCondition classes for implementing an explicit wait. The ExpectedCondition class provides a set of predefined conditions to wait before proceeding further in the code.
An example of an explicit wait is:
1 2 3 | WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.titleContains("selenium")); |
Note: Implicit wait time is applied to all elements in your script and Explicit wait time is applied only for a particular specified element.
How to check if a button is enabled on the page ?
- We can Use isEnabled() method.
- The return type of the method is boolean.
- So if it return true then button is enabled else not enabled.
1 | driver.findElement(By.id(“id_of_element”)).isEnabled(); |
Selenium WebDriver Interview Questions and Answers for Experience
- What is the difference between sleep() and setSpeed() method?
Sleep() and setSleep() both methods are used to delay the speed of execution.
Thread.sleep(): It is used to stop the current (java) thread for the specified period of time. It’s done only once.
- It takes a single argument in integer format.
For Example:
- thread.sleep(5000)- It will wait for 5 seconds.
- It waits only once at the command given at sleep.
setSpeed(): It will stop the execution for every selenium command for specific amount of time.
- It takes a single argument in integer format.
For Example:
- selenium.setSpeed(“5000”)- It will wait for 5 seconds.
- It runs each command after setSpeed delay by the number of milliseconds mentioned in set Speed.
- What are some limitations of selenium?
- We cannot test desktop application using selenium.
- We cannot test web services using selenium.
- For creating robust scripts in selenium webdriver, programming langauge knowledge is required.
- We have to rely on external libraries and tools forperforming tasks like – logging(log4J), testing framework-(testNG, JUnit), reading from external files(POI for excels) etc.
- What is an absolute XPath?
- An absolute XPath is a way of locating an element using an XML expression beginning from root node i.e. html node in case of web pages.
- The main disadvantage of absolute xpath is that even with slightest change in the UI or any element the whole absolute XPath fails.
Example – html/body/div/div[2]/div/div/div/div[1]/div/input
- What is a relative XPath?
- A relative XPath is a way of locating an element using an XML expression beginning from anywhere in the HTML document.
- There are different ways of creating relative XPaths which are used for creating robust XPaths (unaffected by changes in other UI elements).
Example – //input[@id=’username’]
Selenium WebDriver Interview Questions and Answers for Experience
- How can we locate an element by only partially matching its attributes value in Xpath?
- Using contains () method we can locate an element by partially matching its attribute’s value.
- This is particularly helpful in the scenarios where the attributes have dynamic values with certain constant part.
1 | xPath expression = //*[contains(@name,'user')] |
The above statement will match the all the values of name attribute containing the word ‘user’ in them.
Selenium WebDriver Interview Questions and Answers for Experience
- How to switch between multiple windows in selenium?
- Selenium has driver.getWindowHandles() and driver.switchTo().window(“{windowHandleName}”) commands to work with multiple windows.
- The getWindowHandles() command returns a list of ids corresponding to each window and on passing a particular window handle to driver.switchTo().window(“{windowHandleName}”) command we can switch control/focus to that particular window.
1 2 3 4 5 | for (String windowHandle : driver.getWindowHandles()) { driver.switchTo().window(handle); } |
- What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in selenium?
- driver.getWindowHandle() returns a handle of the current page (a unique identifier)
- driver.getWindowHandles() returns a set of handles of the all the pages available.
- How to delete cookies in selenium?
- Using deleteAllCookies() method-
1 | driver.manage().deleteAllCookies(); |
- What is an implicit wait in selenium?
- An implicit wait is a type of wait which waits for a specified time while locating an element before throwing NoSuchElementException.
- As by default selenium tries to find elements immediately when required without any wait. So, it is good to use implicit wait.
- This wait is applied to all the elements of the current driver instance.
1 | driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); |
- What is an explicit wait in selenium?
- An explicit wait is a type of wait which is applied to a particular web element untill the expected condition specified is met.
1 2 3 | WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("elementId"))); |
- What are some expected conditions that can be used in Explicit waits?
- Some of the commonly used expected conditions of an element that can be used with explicit waits are-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | elementToBeClickable(WebElement element or By locator) stalenessOf(WebElement element) visibilityOf(WebElement element) visibilityOfElementLocated(By locator) invisibilityOfElementLocated(By locator) attributeContains(WebElement element, String attribute, String value) alertIsPresent() titleContains(String title) titleIs(String title) textToBePresentInElementLocated(By, String) |
- What is fluent wait in selenium?
- A fluent wait is a type of wait in which we can also specify polling interval(intervals after which driver will try to find the element) along with the maximum timeout value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Wait wait = new FluentWait(driver) .withTimeout(20, SECONDS) .pollingEvery(5, SECONDS) .ignoring(NoSuchElementException.class); WebElement textBox = wait.until(new Function<webdriver,webElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.id("textBoxId")); } } ) |
- What are the different keyboard operations that can be performed in selenium?
The different keyboard operations that can be performed in selenium are-
- .sendKeys(“sequence of characters”)- Used for passing charcter sequesnce to an input or textbox element.
- .pressKey(“non-text keys”)- Used for keys like control, function keys etc that ae non text.
- .releaseKey(“non-text keys”)- Used in conjuntion with keypress event to simulate releasing a key from keyboard event.
- What are the different mouse actions that can be performed?
- The different mouse evenets supported in selenium are
1 2 3 4 5 6 7 8 9 10 11 12 13 | click(WebElement element) doubleClick(WebElement element) contextClick(WebElement element) mouseDown(WebElement element) mouseUp(WebElement element) mouseMove(WebElement element) mouseMove(WebElement element, long xOffset, long yOffset) |
- Write the code to double click an element in selenium?
1 2 3 4 5 | Actions action = new Actions(driver); WebElement element=driver.findElement(By.id("elementId")); action.doubleClick(element).perform(); |
- Write the code to right click an element in selenium?
1 2 3 4 5 | Actions action = new Actions(driver); WebElement element=driver.findElement(By.id("elementId")); action.contextClick(element).perform(); |
Selenium WebDriver Interview Questions and Answers for Experience
- How to mouse hover an element in selenium?
1 2 3 4 5 | Actions action = new Actions(driver); WebElement element=driver.findElement(By.id("elementId")); action.moveToElement(element).perform(); |
Selenium WebDriver Interview Questions and Answers for Experience
- How to verify tooltip text using selenium?
- Tooltips webelements have an attribute of type ‘title’. By fetching the value of ‘title’ attribute we can verify the tooltip text in selenium.
1 | String toolTipText = element.getAttribute("title"); |
- How to locate a link using its text in selenium?
- Using linkText() and partialLinkText() we can locate a link.
- The difference between the two is linkText matches the complete string passed as parameter to the link texts.
- Whereas partialLinkText matches the string parameter partially with the link texts.
1 2 3 | WebElement link1 = driver.findElement(By.linkText(“artOfTesting”)); WebElement link2 = driver.findElement(By.partialLinkText(“artOf”)); |
- What are DesiredCapabilities in selenium webdriver?
- Desired capabilities are a set of key-value pairs that are used for storing or configuring browser specific properties like its version, platform etc. in the browser instances.
- What are some commonly encountered exceptions in selenium?
- NoSuchElementException – When no element could be located from the locator provided.
- ElementNotVisibleException – When element is present in the dom but is not visible.
- NoAlertPresentException – When we try to switch to an alert but the targetted alert is not present.
- NoSuchFrameException – When we try to switch to a frame but the targetted frame is not present.
- NoSuchWindowException – When we try to switch to a window but the targetted window is not present.
- UnexpectedAlertPresentException – When an unexpected alert blocks normal interaction of the driver.
- TimeoutException – When a command execution gets timeout.
- InvalidElementStateException – When the state of an element is not appropriate for the desired action.
- NoSuchAttributeException – When we are trying to fetch an attribute’s value but the attribute is not correct
- WebDriverException – When there is some issue with driver instance preventing it from getting launched.
- How can we capture screenshots in selenium?
- Using getScreenshotAs method of TakesScreenshot interface we can take the screenshots in selenium.
1 2 3 | File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg")); |
- How to handle dropdowns in selenium?
1 2 3 4 5 6 7 8 | Select countriesDropDown = new Select(driver.findElement(By.id("countries"))); dropdown.selectByVisibleText("India"); //or using index of the option starting from 0 dropdown.selectByIndex(1); //or using its value attribute dropdown.selectByValue("Ind"); |
- How to check which option in the dropdown is selected?
- Using isSelected() method we can check the state of a dropdown’s option.
1 2 3 4 5 | Select countriesDropDown = new Select(driver.findElement(By.id("countries"))); dropdown.selectByVisibleText("India"); //returns true or false value System.out.println(driver.findElement(By.id("India")).isSelected()); |
Selenium WebDriver Interview Questions and Answers for Experience
- How can we check if an element is getting displayed on a web page?
- Using isDisplayed method we can check if an element is getting displayed on a web page.
1 | driver.findElement(By locator).isDisplayed(); |
Selenium WebDriver Interview Questions and Answers for Experience
- How can we check if an element is enabled for interaction on a web page?
- Using isEnabled method we can check if an element is enabled or not.
1 | driver.findElement(By locator).isEnabled(); |
- What is Robot API?
- Robot API is used for handling Keyboard or mouse events.
- It is generally used to upload files to the server in selenium automation.
1 2 3 4 | Robot robot = new Robot(); //Simulate enter key action robot.keyPress(KeyEvent.VK_ENTER); |
- How to handle HTTPS website in selenium? / How to accept the SSL untrusted connection?
- Using profiles in firefox we can handle accept the SSL untrusted connection certificate. Profiles are basically set of user preferences stored in a file.
1 2 3 4 5 6 7 | FirefoxProfile profile = new FirefoxProfile(); profile.setAcceptUntrustedCertificates(true); profile.setAssumeUntrustedCertificateIssuer(false); WebDriver driver = new FirefoxDriver(profile); |
- How to do drag and drop in selenium?
- Using Action class, drag and drop can be performed in selenium.
1 2 3 4 5 6 7 8 9 10 11 | Actions builder = new Actions(driver); Action dragAndDrop = builder.clickAndHold(SourceElement) .moveToElement(TargetElement) .release(TargetElement) .build(); dragAndDrop.perform(); |
- How to execute javascript in selenium?
1 2 3 4 5 6 7 | JavaScript can be executed in selenium using JavaScriptExecuter. Sample code for javascript execution- WebDriver driver = new FireFoxDriver(); if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor)driver).executeScript("{JavaScript Code}"); } |
- How to handle alerts in selenium?
- In order to accept or dismiss an alert box the alert class is used.
- This requires first switching to the alert box and then using accept() or dismiss() command as the case may be.
1 2 3 4 5 6 7 | Alert alert = driver.switchTo().alert(); //To accept the alert alert.accept(); Alert alert = driver.switchTo().alert(); //To cancel the alert box alert.dismiss(); |
- What is HtmlUnitDriver?
- HtmlUnitDriver is the fastest WebDriver. Unlike other drivers (FireFoxDriver, ChromeDriver etc), the HtmlUnitDriver is non-GUI, while running no browser gets launched.
- How to handle hidden elements in Selenium webDriver?
- Using javaScript executor we can handle hidden elements-
1 | (JavascriptExecutor(driver)) .executeScript("document.getElementsByClassName(ElementLocator).click();"); |
- What is Page Object Model or POM?
- Page Object Model (POM) is a design pattern in selenium.
- A design pattern is a solution or a set of standards that are used for solving commonly occurring software problems.
- POM helps to create a framework for maintaining selenium scripts.
- In POM for each page of the application a class is created having the web elements belonging to the page and methods handling the events in that page.
- The test scripts are maintained in separate files and the methods of the page object files are called from the test scripts file.
- What are the advantages of POM?
- Using POM we can create an Object Repository, a set of web elements in separate files along with their associated functions. Thereby keeping code clean.
- For any change in UI(or web elements) only page object files are required to be updated leaving test files unchanged.
- It makes code reusable and maintain able.
- What is Page Factory?
- Page factory is an implementation of Page Object Model in selenium.
- It provides @FindBy annotation to find web elements and PageFactory.initElements() method to initialize all web elements defined with @FindBy annotation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class SamplePage { WebDriver driver; @FindBy(id="search") WebElement searchTextBox; @FindBy(name="searchBtn") WebElement searchButton; //Constructor public samplePage(WebDriver driver){ this.driver = driver; //initElements method to initialize all elements PageFactory.initElements(driver, this); } //Sample method public void search(String searchTerm){ searchTextBox.sendKeys(searchTerm); searchButton.click(); } } |
- What is a data driven framework?
- A data driven framework is one in which the test data is put in external files like csv, excel etc separated from test logic written in test script files.
- The test data drives the test cases, i.e. the test methods run for each set of test data values.
- TestNG provides inherent support for data driven testing using @dataProvider annotation.
- What is a keyword driven framework?
- A keyword driven framework is one in which the actions are associated with keywords and kept in external files e.g. an action of launching a browser will be associated with keyword – launchBrowser(), action to write in a textbox with keyword – writeInTextBox(webElement, textToWrite) etc.
- The code to perform the action based on a keyword specified in external file is implemented in the framework itself.
- What is a hybrid framework?
- A hybrid framework is a combination of one or more frameworks.
- Normally it is associated with combination of data driven and keyword driven frameworks where both the test data and test actions are kept in external files(in the form of table).
- What is selenium Grid?
- Selenium grid is a tool that helps in distributed running of test scripts across different machines having different browsers, browser version, platforms etc in parallel.
- In selenium grid there is hub that is a central server managing all the distributed machines known as nodes.
- What are some advantages of selenium grid?
The advantages of selenium grid are-
- It allows running test cases in parallel thereby saving test execution time.
- Multi browser testing is possible using selenium grid by running the test on machines having different browsers.
- It is allows multi-platform testing by configuring nodes having different operating systems.
Selenium WebDriver Interview Questions and Answers for Experience
- What is a hub in selenium grid?
- A hub is server or a central point in selenium grid that controls the test executions on the different machines.
Selenium WebDriver Interview Questions and Answers for Experience
- What is a node in selenium grid?
- Nodes are the machines which are attached to the selenium grid hub and have selenium instances running the test scripts.
- Unlike hub there can be multiple nodes in selenium grid.
Selenium WebDriver Interview Questions and Answers for Experience
- Explain the line of code Webdriver driver = new FirefoxDriver();.
- In the line of code Webdriver driver = new FirefoxDriver(); ‘WebDriver’ is an interface and we are creating an object of type WebDriver instantiating an object of FirefoxDriver class.
Selenium WebDriver Interview Questions and Answers for Experience
- Name an API used for reading and writing data to excel files.
- Apache POI API and JXL (Java Excel API) can be used for reading, writing and updating excel files.