SELENIUM INTERVIEW QUESTIONS
dragAndDrop(source, target)
: Invokes click-and-hold at the source location and moves to the location of target element before releasing the mouse. source - element to grab, target - element to release.
A ClassName operator uses a...
A ClassName operator uses a class attribute to identify an object.
17. What are operations can you do using the actions class?
Actions builder = new Actions(driver); Action mouseOverHome = builder.moveToElement(link_Home).build();
31. Scenario: you have 2 frames on the page and in 1 you need to enter some text in the second you need to click a button. Can you switch from frame to frame directly?
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.
16. What are the types of waits available in Selenium WebDriver? What is Implicit/ Explicit/ Fluent Wait In Selenium WebDriver?
Implicit Wait Explicit Wait Fluent Wait
22. How do you handle the calendar elements? WebTables?
Step 1 - Click on the calendar Step 2 - Get all td of tables using the find elements method Step 3 - using for loop get the 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.
We need to know that WebDriver is an
interface in selenium and ChromeDriver and FirefoxDriver is class. We can not instantiate the WebDriver with new WebDriver since it is interface.
If the <select > tag contains multiple attributes, it means
that the dropdown allows selecting multiple values. We can use the isMultiple() Method to check the webelement allowing the multiple select. Select slt = new Select(driver.findElement(By.xpath("//select[@id='FromLB']"))); if (slt.isMultiple()){ listbox.selectByVisibleText("Value"); listbox.selectByVisibleText("Value"); }
Advantages of Using CSS Selector
• It's faster than XPath. • It's much easier to learn and implement. • You have a high chance of finding your elements. • It's compatible with most browsers to date.
// instantiate an instance of ChromeDriver, which will be driving our browser:
• WebDriver driver = new ChromeDriver();
How to launch a browser using Selenium WebDriver?
// set the property for chrome driver, specify its location via the webdriver.chrome.driver : • System.setProperty("webdriver.chrome.driver", "/absolute/path/to/binary/chromedriver");
33. Write a dynamic XPath to locate a table's 2nd row 3rd column data.
//to get 2nd row 3rd column data WebElement cellIneed = tableRow.findElement(By.xpath("//table/tbody/tr[2]/td[3]"));
Steps to execute:
1. Get the handle of the parent window using the command: String parentWindowHandle = driver.getWindowHandle(); 2. Print the window handle of the parent window. 3. Find the element on the web page using an ID which is an element locator. 4. Open multiple child windows. 5. Iterate through child windows. 6. Get the handles of all the windows that are currently open using the command: Set<String> allWindowHandles = driver.getWindowHandles(); which returns the set of handles. 7. Use the switchTo command to switch the target window.
Alert Interface. Second method that we would be using along with the Alert interface.
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();
Alert Interface. Third method that we would be using along with the Alert interface.
3) String getText() - The getText() method returns the text displayed on the alert box. alert.getText(); or driver.switchTo().alert().getText();
Alert Interface. Fourth method that we would be using along with the Alert interface.
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 up, for that we can use AutoIT.
Selenium supports the following locators:
ClassName • cssSelector • Id • linkText • name • partialLinkText • tagName • xpath
clickAndHold()
Clicks at present mouse location without releasing
3. What are the types of WebDriver APIs available in Selenium? What is a headless browser?
Different webdriver API: ● Gecko Driver ● InternetExplorer Driver ● Chrome Driver ● Safari Driver ● HTMLUnit Driver
● doubleClick ()
Double clicks on Element
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 do you handle the multiple windows/tabs in selenium? EXAMPLE
Example: Iterator<String> iterator = allWindowHandles.iterator(); // Here we will check if child window has other child windows and will fetch the heading of the child window while (iterator.hasNext()) { String ChildWindow = iterator.next(); if (!mainWindowHandle.equalsIgnoreCase(ChildWindow)) { driver.switchTo().window(ChildWindow); WebElement text = driver.findElement(By.id("sampleHeading")); System.out.println("Heading of child window is " + text.getText()); } }
Examples using Xpath
Examples: • /bookstore/book/price[text()] • //div[@class='value'] • //div[.='textValue'] • //a[text()='textValue]
Alert Interface. First method that we would be using along with the Alert interface.
First, instantiate 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();
Sel Open-source suite of tools mainly used for...
Functional and Regression Test Automation.
● Selenium supports various programming environments to write programs (Test scripts) like...
Java, C#, Python, Perl, Ruby, PHP, JS
25. Is it possible to automate the captcha using Selenium?
List some scenarios which we cannot automate using Selenium WebDriver? No, we can't automate captcha. Less Support for Image-based Testing, No Other Tool integration for Test management
Selenium supports various Operating environments like...
MS Windows, Linux, Macintosh etc...
partialLinkText can...
Part of the text in the link can also identify an element
contextClick()
Performs a context-click (right click) on an element
Selenium IDE:-
Selenium IDE is a Firefox plugin which is used to create and execute test cases • It records and plays back the interactions which the user had with the web browser • Using IDE, you can export the programming code in different languages: Java, Ruby, Python and so on
Most commonly used tools in selenium are
Selenium and QTP
● click ()
Simply click on element
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]
24. How can you find Broken Links/Images in a page using Selenium WebDriver?
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 into it. ● Now Create a Connection using URL object( i.e ., link) ● Connect using the Connect Method. ● Use getResponseCode () to get response code. go on questions to see an example
How to get the text of a web element? How to get an attribute value using Selenium WebDriver?
String buttonText = driver.findElement(By.cssSelector("div.success")).getText(); String innerText = driver.findElement(By.xpath("/div/td ")). getAttribute("innerHTML");
linkText is text used in...
Text used in hyperlinks can also locate element
What is CSS Selector?
The CSS selectors identify the various elements in the DOM, and they affect or connect to these parts of the interface.
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("x"));
Implicit Wait
The implicit wait will tell to 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 exception. driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
4. What are the Locators available in Selenium? Which locator do you prefer?
There are various types of locators, using which we can identify a web element uniquely on the Webpage.
20. How to pause a test execution?
Thread.sleep(1000);
30. How To Login Into Any Site If It Is Showing Any Authentication Pop-Up for a Username And Password?
To do this we pass username and password with the URL http://username:password@url e.g. http://myUserName:[email protected] Testing URL: https://www.techtorialacademy.com/ Code: driver.get("https://www.techtorialacademy.com/");
34. Let's say I have a page and on that page have web table that have 4 columns and twenty rows. And I have to validate data in the last rows?
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<WebElement> 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<WebElement> rows = driver.findElements(By.xpath("//table[@summary='Sample Table']/tbody/tr"));
18. How To Perform Right-Click (Context Click), Double Click and hover-over in Selenium?
Using action class we can perform all of these operations Actions action = new Actions(driver); WebElement element=driver.findElement(By.linkText("TEST")); //To Double click action.doubleClick(element).perform(); //To Mouse over action.moveToElement(element).perform(); //To Right Click action.contextClick(element).perform(); //To mouse over WebElement element = driver.findElement(By.name("source")); WebElement target = driver.findElement(By.name("target")); action.dragAndDrop(element, target).perform();
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.
Wait wait = new FluentWait(WebDriver reference) .withTimeout(timeout, SECONDS) .pollingEvery(timeout, SECONDS) .ignoring(Exception.class);
Selenium WebDriver:-
We are using the Selenium 3.141 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. • Selenium WebDriver is a tool used to automate testing for web application • It allows us to execute tests against different browsers like Firefox, Chrome, IE & Safari • Selenium WebDriver eliminated the use of Selenium Server thus making it work faster than RC
13. How do you handle the multiple windows/tabs in selenium?
We can handle multiple windows/tabs in selenium webdriver using Switch To methods which will allow us to switch control from one window to another window.
20. How To Scroll Web Page Down Or Up Using Selenium WebDriver?
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 js = (JavascriptExecutor) driver; js.executeScript("arguments[0].scrollIntoView(true);",element);
What is an XPath?
XPath is used to locate the elements. Using XPath, we could navigate through elements and attributes in an XML document to locate web elements.
What Is XPath?
XPath stands for XML Path. It's a query language that helps identify elements from an XML document.
Id can ...
also identify elements by using the 'id' attribute and its similar to class in that form
21. How to press the ENTER key on text box In Selenium WebDriver?
driver.findElement(By.id("IdValue")).sendKeys(Keys.RETURN); or driver.findElement(By.id("IdValue")).sendKeys(Keys.ENTER); or driver.findElement(By.id("IdValue")).sendKeys(Keys.TAB);
// navigate to the specific url :
driver.get("https://www.techtorialacademy.com/");
findElement() returns...
findElement() returns only single WebElement and if that element is not located or we use some wrong selector then it throws NoSuchElementexception. • WebElement searchButton=driver.findElement(By.id("Value));
tagName We can also use a tag to
locate elements
findElements() returns List of WebElements -
returns empty list, when element is not found on current page as per the given element locator mechanism. It doesn't throw NoSuchElementException. • List<WebElement> names=driver.findElements(By.id("Value"));
27. How to Upload and Download a file in Selenium WebDriver?
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"); If you want to upload the file in Selenium without sending the key of the files, we need to use Robot class or get help from other tools like AutoIT or Sikuli etch.
CSS is used to create...
style rules for webpages and can be used to identify any web element.
Selenium Grid:-
• Selenium Grid is used for parallel testing or distributed testing. It allows us to execute test scripts parallelly on different machines
Selenium RC:-
• Selenium Remote Control (RC) is used to write test cases in different Programming languages • In Selenium IDE, we can run the recorded scripts only in Firefox browser, whereas, in Selenium RC, we can run the recorded script in any browser like IE, Chrome, Safari, Opera and so on
We can also set the driver using webdriverManager. We need to put one dependency to the pom.xml file:
• WebDriverManager.chromedriver().setup();
Advantages of Using XPath
• XPath allows you to navigate up the DOM when looking for elements to test or scrape. • It's compatible with old browsers (or it was at time of publishing—including older versions of Internet Explorer, which some corporations still use). • Creating in XPath is more flexible than in CSS Selector.
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
29. What are the open-source Frameworks supported by Selenium WebDriver?
● JUnit ● TestNG ● Cucumber ● JBehave
We can perform following operation using action class:
● click () ● doubleClick () ● contextClick() ● clickAndHold() ● dragAndDrop(source, target)
Name attribute can also identify an
element
28. What are the different exceptions you have faced in Selenium WebDriver? What is StaleElementReference Exception?
● ElementNotVisibleException ● NoSuchElementException ● NoSuchFrameException ● NoAlertPresentException ● NoSuchWindowException ● StaleElementReferenceException - WebDriver throw this exception when an element is in the DOM and even visible on the screen but you can't access the element as DOM reference change. This can happen if a DOM operation happening on the page is temporarily causing the element to be inaccessible. Sometimes once we click the some button on the page using automation the page might refresh, this one also cause the stale element exception.
StaleElementReferenceException
- WebDriver throw this exception when an element is in the DOM and even visible on the screen but you can't access the element as DOM reference change. This can happen if a DOM operation happening on the page is temporarily causing the element to be inaccessible. Sometimes once we click the some button on the page using automation the page might refresh, this one also cause the stale element exception.
1. What is Selenium? Why do you prefer Selenium Automation Tool? What is the limitation of Selenium?
1. Selenium is a suite of software tools to automate Web Browsers. Prefer to Use Selenium Tool
Examples of using CCS Selector
Examples: • div[id='value'] • div[class*='value']
● Selenium supports various Browsers like..
Mozilla Firefox, IE, Google Chrome, Safari, Opera etc...
solution to StaleElementReferenceException
Solution: We could refresh the page and try again for the same element. or Wait for the element till it gets available wait.until(ExpectedConditions.presenceOfElementLocated(By.id("id"))); Or we can initialize the web elements again using page factory in page object model. Like: PageFactory.initelements(driver, HomePage.class);
18. How to handle hidden elements in Selenium WebDriver?
The first store that element in the 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);
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.
getWindowHandle()
This method helps to get the window handle of the current window. Return type of this method is current window id in String data type. • String handle= driver.getWindowHandle();
14. How to do you handle the iframe in selenium?
Using switch commands we can switch to the different frame to handle elements: We can switch to the frame in 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("Iframe1 ")); driver.switchTo().frame(iframeElement); 3. Switch to Frames by Index driver.switchTo().frame(indexNumber)
15. How can we handle web-based pop-ups? How can you handle JavaScript Alerts?
We can handle web-based pop-ups using Alert Interface. There are four methods that we would be using along with the Alert interface.
19. How to input text in the text box using Selenium WebDriver?
We can input text using sendkeys() WebElement email = driver.findElement(By.id("email")); email.sendKeys("[email protected]"); as well as JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("document.getElementById('email') .value='[email protected]';");
12. How to select a value in a dropdown? Is it possible to select multiple values in dropdown?
We can use Select class to select the value from dropdown. Select select = new Select(driver.findElement( By.id("select"))); ● select.selectByVisibleText("Value"); ● select.selectByIndex(1); ● select.selectByValue("value");
32. Scenario: there is a submit button on the page it has id property. By using id we got element not found exception, how will you handle this situation? What might be the problem in this case?
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.
How do you work with radio buttons which do not have an id attribute?
We can use click() if "id" is not present we can use XPath(i.e you can use relative or absolute), CSS, or another 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.
23. How to capture screenshots in Selenium WebDriver?
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);
Xpath
Xpath is the language used to query the XML document. The same can uniquely identify the web element on any page.
26. Have you done any cross-browser testing within your Project?
Yes, I have done cross-browser testing in my framework using 3 browser initialization. Chrome, IE, and Firefox testing using Webdriver. I stored my browser name in the configuration properties file and was able to change the browser from there easly.
7. What is the difference between driver.close() and driver. quit() methods?
close() - It is used to close the browser or page currently which is having the focus. quit() - It is used to shut down the webdriver instance or destroy the web driver instance(Close all the windows).
HTMLUnitDriver is the fastest because....
it is headless browser which have less User Interface Super interface of WebDriver is SearchContext Interface.
getWindowHandles()
method or commands returns all handles from all opened browsers by Selenium WebDriver during execution. Return a set of window handle. It returns the set of unique window ids from the windows. • Set<String> allWindowHandles= driver.getWindowHandles();
Calendar handling
public class CalendarHandling { public static void main(String[] args){ System.setProperty("webdriver.firefox.marionette", "G:\\Selenium\\Firefox driver\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("URL) driver.findElement(By.id("datepicker")).click(); List<WebElement> allDates = driver.findElements(By.xpath("//table[@class='techtorialclndr']//td")); for(WebElement ele:allDates) { String date=ele.getText(); if (date.equalsIgnoreCase("28")) { ele.click(); break; } } }
8. What is the alternative to driver.get() method to open a URL using Selenium WebDriver? What is the difference?
• driver.navigate().to("https://www.techtorialacademy.com/"); The navigate interface also exposes the ability to move backward and forwards in our browser's history: • driver.navigate().forward(); • driver.navigate().back();