This document was ed by and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this report form. Report 2z6p3t
Overview 5o1f4z
& View Selenium Interview Questions as PDF for free.
Table of Contents Different types locators that can be used locate elements in Selenium Classes should not have spaces in between them If there are multiple tagnames and you do not specify attribute, Selenium identifies the first one When xpath starts with html-Not reliable- Switch browser to get another one How construct customized Xpath? How construct customized CSS selector? How construct customized Xpath using regular expression? How construct customized CSS selector using regular expression? How validate customized Xpath locator in browser console? How validate customized CSS selector locator in browser console? What is the difference between Relative and absolute xpath? How to traverse to sibling element using xpath? How to traverse back to Parent element from Child element using Xpath? How to identify element with Text based? Giving identifying using parent-child xpath locators Using static dropdown using Select class WebElement methods Alerts Different types of waits How to use implicit waits? How to use explicit waits? Action class can be used for performing special Mouse and Keyboard interactions in Selenium. Following are the actions that can be performed and the Action class methods that are used: Actions class Example: Mouse over an object code demo Actions class Example: Drag and drop
Page |2
Performing composite actions (multiple) actions Handling multiple browser windows: Switching to Child window Switching between frames How to check if an element is present in the web page? Where and when can you use Selenium’s javascript executor? Code for Javascript executor for Autosuggestion boxes How to accept insecure and SSL certificates in Selenium? Maximizing and minimizing windows in Selenium Deleting cookies Taking screenshot in Selenium
Page |3
Selenium Interview Questions
Locators 1. Different types locators that can be used locate elements in Selenium A. You can locate elements in Selenium using By class. Following are the locators in By class you can use: 1. name 2. className 3. linkText 4. id 5. xpath 6. cssSelector 7. partialLinkText 8. tagName 9. js (new method) 2. Classes should not have spaces in between them A. Example: <- Not allowed Above compound classes attribute cannot be accepted. Selenium will throw compound class exception for this 3. If there are multiple tagnames and you do not specify attribute, Selenium identifies the first one A. B. If you try selecting using only tagname and value, selenium will return the first found element, which is input tag for name. C. Selenium scans from top left for each tag 4. When xpath starts with html-Not reliable- Switch browser to get another one A. Sometimes, browser returns xpath from html/body/div/… B. Such xpaths are not usually accurate, since it may break when developer makes any change to the html 5. How construct customized Xpath? A. B. Syntax: //tagName[@attribute='value'] C. Example: //input[@id=’email’]
Page |4
6. How construct customized CSS selector? A. B. Syntax: tagName[attribute='value'] C. Example: input[id=’email’] D. Syntax for choosing id attributes: tagName#id E. Example for choosing id attribute: input#email F. Syntax for choosing class attributes: tagName.classname G. Example for choosing class attribute: input.name 7. How construct customized Xpath using regular expression? A. B. Syntax: //tagName[contains(@attribute, 'value')] C. Example: //input[contains(@class, ’’)] D. Above example will return input tag which has name as class 8. How construct customized CSS selector using regular expression? A. B. Syntax: tagName[atrribute*='value'] C. Example: input[class*= ’’] D. Above example will return input tag which has name as class 9. How validate customized Xpath locator in browser console? A. B. Syntax: $x(“xpath”) C. Example: $x(“input[class*= ’’]”) 10. How validate customized CSS selector locator in browser console? A. B. Syntax: $(“cssselector”) C. Example: $(“input[class*= ’’]”) 11. What is the difference between Relative and absolute xpath? A. Relative- You can directly access the node using xpath. In other words, we do not depend on parent nodes to access the child nodes Eg. $x(“//input[id=’name’]”) B. Absolute xpath – We traverse from root node. We use parent nodes to Parent/child Eg. $x("//form[@id='tsf']/div[2]/div/div/div/div/input")
Page |5
12. How to traverse to sibling element using xpath? A. Example: .//*[@id='tablist1-tab1']/following-sibling::li[2] Above we are traversing to the 2nd sibling from the currently selected one.
Item1
Item2
Item3
<- Returns this node
13. How to traverse back to Parent element from Child element using Xpath? A. Example: .//*[@id='tablist1-tab1']/parent::ul
<- Returns this node
Item1
Item2
Item3
14. How to identify element with Text based? A. Example: //*[text()=’ Item2 ’] We are selecting a node having text ‘ Item2 ’
Item1
Item2
Item3
<- Returns this node
15. Giving identifying using parent-child xpath locators A. We can locate an element using parent-child xpath locators $x(“//ul[@class = ‘responsive-tabs_list’] //li[@id=’tablist1-tab3’]”) Example:
Item1
Item2
Item3
<- Returns this node
Page |6
16. Using static dropdown using Select class We use Selenium class called Select to select options from dropdown menu To use select we, WebElement object to the Select class’ constructor Then, we use Select class methods selectByValue(), selectByIndex() or selectByVisibleText() to: Code: Select s = new Select(driver.findElement(By.id(“month”)) ); s.selectByValue(“2”); s.selectByIndex(5); s.selectByVisibleText(“Aug”); HTML: <select aria-label="Month" name="birthday_month" id="month" title="Month" class="_5dba"> <- s.selectByValue(“2”) returns this node <- s.selectByIndex(5) returns this node <- s.selectByVisibleText(“Aug”) returns this node 17. WebElement methods getAttribute(String name) -Get the value of the given attribute of the element. getCssValue(String propertyName) -Get the value of a given CSS property getTagName() -Get the tag name of this element getText() -Get the visible (i.e. not hidden by CSS) text of this element, including sub-elements. isDisplayed() -Is this element displayed or not? This method avoids the problem of having to parse an element's "style" attribute.
isEnabled() -Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
Page |7
isSelected() -Determine whether or not this element is selected or not. Often used with checkboxes
submit() -If this current element is a form, or an element within a form, then this will be submitted to the remote server.
Alerts 18. Alerts We can handle alerts by using switchto() method of the WebDriver (object) WebDriver.switchto().alert() Methods that can be run: To press ok or accept etc. we use accept() WebDriver.switchto().alert().accept(); To dismiss, quit or exit an alert, we use method dismiss() WebDriver.switchto().alert().dismiss(); To get the text of the alert, we use getText() WebDriver.switchto ().alert().getText(); To input text, we use sendKeys() WebDriver.switchto().alert().sendKeys(String keysToSend);
Synchronization (Waits) 19. Different types of waits • Implicit wait • Explicit wait • Fluent wait • Thread.sleep 20. How to use implicit waits? Implicit waiting can be triggered by using following call: WebDriver.manage().timeouts().implicitlyWait(long time, TimeUnit unit); Ex.; WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Page |8
21. How to use explicit waits? In Explicit wait, we until a condition is fulfilled. We can trigger explicit waits by creating WebDriverWait object and calling until() method of the class ing the conditions on which to satisfy WebDriverWait.until(Function isTrue) Ex.: WebDriver driver = new ChromeDriver(); WebDriverWait dWait = new WebDriverWait(drive, 20); dWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='article[1]"))); driver.findElement(By.xpath("//div[@id='article[1]")).click();
ACTIONS, FRAMES AND MULTIPLE WINDOWS 22. Action class can be used for performing special Mouse and Keyboard interactions in Selenium. Following are the actions that can be performed and the Action class methods that are used: 1. Mouseover an object [ Actions.moveToElement() ] 2. Context click (right click) [ Actions.contextClick() ] 3. Double click [ Actions.doubleClick() ] 4. Drag and drop [ Actions.dragAndDrop() ] 5. Typing in capital letters [ Actions.keyDown() ] Notes on Actions class: Multiple actions can be stacked using build() and perform() methods exposed by the Actions class. They are necessary to execute the action. Action build() -Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).
void perform() - A convenience method for performing the actions without calling build() first.
23. Actions class Example: Mouse over an object code demo Mouse over an object is when mouse is moved (and hovers over an element in a web page). This can be used to show detailed sub-menu or instructions Code: WebDriver driver = new ChromeDriver(); driver. get(“https://www.amazon.com/”); Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.cssSelector(“a[id = ‘nav-linklist.’]”))).build().perform();
Page |9
24. Actions class Example: Drag and drop Drag and drop action can be performed by method dragAndDrop() in Actions class. WebDriver driver = new ChromeDriver(); driver. get(“https://jqueryui.com/droppable/”); Actions action = new Actions(driver); WebElement source = driver.findElement(By.id(“draggable”)); WebElement target = driver.findElement(By.id(“droppable”)); action.dragAndDrop(source, target).build().perform();
25. Performing composite actions (multiple) actions Ex. We want to click in a text box to take the cursor and then type text in capital letters and then select the entered text using double click action. action.moveToElement(driver.findElement(By.id(“searchtextbox”))).click().keyDown(Keys.SHI FT).sendKeys(“John”).doubleClick().build().perform();
26. Handling multiple browser windows: Switching to Child window Even if there are multiple windows, by default, Selenium always searches for elements in the parent window (first launched). If you want to switch to any of the child windows, you need to switch to different window. You can do this by using method: WebDriver.switchTo().window(handle) To switch to child window, we do the following: 1. Get all the window handles of the currently open windows. List of open window handles are returned as Set. 2. Get an iterator to iterate to a specific window from the Set 3. Use the next() method to visit each of the child windows. that the respective window handles are stored in the iterator 4. Now switch to the new window by ing the window handle as a parameter. Now you can search for elements and run tests on the child window 5. Below is the code: Set<String> ids = driver.getWindowHandles(); Iterator<String> iter = ids.iterator(); String parentId = iter.next(); String childId = iter.next(); driver.switchTo().window(childID);
P a g e | 10
27. Switching between frames Elements under Frames (frame, iframe tags) are not accessible to selenium directly. To access an element inside a frame, one needs to switch to a frame. Following are the methods to switch to a frame: WebDriver.switchTo().window(int index); WebDriver.switchTo().window(String Id); WebDriver.switchTo().window(WebElement); Example: …. <iframe class=”demo-frame”>
Code to switch into and out of frame : WebElement targetFrame = driver.findElement(By.className(“demo-frame”)); driver.switchTo().frame(targetFrame); ….Do something…. driver.switchTo.defaultContent(); //Switches back to the original page
28. How to check if an element is present in the web page? To find if an element is present, we first find all the elements with the locator (xpath, cssSelector, id etc.). If any number of elements are present, they will be returned as a list. We get the size of the list. If size is equal to 0, element is not present; if greater than 0, element is present. This is especially useful if you have multiple frames and you want to locate the element but don’t know in which frame the element is present. Of course, you need to find the element’s xpath (or other locators). 29. Where and when can you use Selenium’s javascript executor? Javascript executor method is useful when you cannot get dynamic elements through normal Selenium methods. The html elements are either hidden or not accessible directly by selenium. More prominent example where you need to use Javascript executors are when
P a g e | 11
you want to retrieve Autosuggestion text box’s suggestions. Since these suggestions are displayed only when partially types input and are thus generated dynamically, it is often not possible to get the locator of the suggestion text. When you try to inspect the suggestion elements, they just often disappear. In such cases, you can use javascript executor methods to read the elements using DOM (instead of Selenium). 30. Code for Javascript executor for Autosuggestion boxes WebDriver driver=new ChromeDriver(); driver.get("https://www.ksrtc.in"); driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys("BENG"); Thread.sleep(2000); driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys(Keys.DOWN); System.out.println(driver.findElement(By.xpath("//input[@id='fromPlaceName']")).getText()); //Javascript DOM can extract hidden elements //because selenium cannot identify hidden elements - (Ajax implementation) //investigate the properties of object if it has any hidden text //JavascriptExecutor JavascriptExecutor js= (JavascriptExecutor)driver; String script = "return document.getElementById(\"fromPlaceName\").value;"; String text=(String) js.executeScript(script); System.out.println(text); int i =0; //BENGALURU INTERNATIONAL AIRPORT while(!text.equalsIgnoreCase("BENGALURU INTERNATIONAL AIRPORT")) { i++; driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys(Keys.DOWN); text=(String) js.executeScript(script); System.out.println(text); if(I > 10) { break; } } if(I > 10) { System.out.println("Element not found"); } else { System.out.println("Element found"); }
P a g e | 12
31. How to accept insecure and SSL certificates in Selenium? We use instantiate Selenium class DesiredCapabilities and call its method acceptInsecureCerts() or setCapability() which sets properties. The DesiredCapabilities object is ed to ChromeOptions class’s merge() method. The ChromeOptions is is a parameter ed to the WebDriver constructor. Code: DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.acceptInsecureCerts(); // Use this //OR capabilities.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true); capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); ChromeOptions chrOptions= new ChromeOptions(); chrOptions.merge(capabilities); System.setProperty("webdriver.chrome.driver", "D:\\devel\\ chromedriver.exe"); WebDriver driver=new ChromeDriver(chrOptions);
32. Maximizing and minimizing windows in Selenium driver.manage(),window().maximize(); driver.manage(),window().minimize();
33. Deleting cookies To delete all cookies: driver.manage().deleteAllCookies(); To delete specific cookie, we the cookie name as parameter: driver.manage().deleteCookieNamed(“sessionKey_aas34w1”);
34. Taking screenshot in Selenium Screehshots can be captured using TakeScreenshot class: File img = ((TakeScreenshot)driver).getScreenshotAs(OutputType.FILE); //We need FileUtils class from Apache: org.apache.commons.io.FileUtils //We save the above screenshot in a file FileUtils.copyFile(img, new File(C://Documents//screenshot.png)); Note: If you try to save the file to C: (eg. C:// screenshot.png) you will get Access violation error. So create a directory under C: drive or save it in some sub directory under C:
Related Documents c2h70
August 2020 0
Selenium Java Interview Questions 5a1m2n
July 2020 2
Selenium Interview Questions 216u1q
August 2020 0
Selenium Interview Questions 216u1q
January 2021 0
Selenium Interview Questions And Answers 6d6130
October 2019 67
100 Best Selenium Job Interview Questions 2j3a1k
August 2020 0
More Documents from "Sujit Tupe" 4o6xj
Selenium Interview Questions 216u1q
August 2020 0
Powermill2017-5axis_6-1-2017.pdf 694i2e
November 2019 122
Third Party Logistics_final Report 2l1b6a
April 2020 29
Harpic Case Study Analysis 1u5e5
December 2019 58
Strategic Management Short Project For Tata Motors 6j4w6g