Selenium Flashcards
- What is Selenium and what is composed of?
- Selenium is a suite of tools for automated web testing. It is composed of;
*Selenium IDE(Integrated Development Environment); a Firefox plugin that works for recording and playing back. - Selenium RC(Remote Control) (1.0) ; is a test tool and is used to work on JS to automate the web application. (2004)
- WebDriver (2.0); is a web automation framework and allows you to execute your tests in different browsers. (2011)
- Selenium Grid; allows tests to run in parallel across multiple machines.
- What are the advantages of Selenium?
- Selenium is open source and free to use without any licensing cost
- It supports multiple languages like Java, Ruby, Python, C#…
- It supports multi-browser testing
- It has a good amount of resources and helping community
- It supports many operating systems like Windows, Mac, Linux …
- Interact with the web application
- What are the disadvantages of Selenium?
- Selenium supports only web-based applications, does not support windows-based application
- No built-in reporting tool, it needs third party tools for report generation activity
- Cannot work with graphics, captchas, barcodes, shapes
- It does not support file upload facility.
- Hard to master, requires developer level knowledge
- Hard to write good locators
- Hard to synchronize
- What are the limitations of Selenium?
- We cannot test desktop application
- We cannot test web services
- Ewe have to use external libraries and tools for performing tasks like testing framework (TestNG, JUnit), reading from
external files (Apache POI for excel) - Automating Captcha is not possible using Selenium
- It does not support file upload facility.
- What types of testing you automate with Selenium?
- functional tests (positive/negative, UI)
- smoke tests
- regression tests
- integration tests
- end to end testing
- data driven
- What we don’t do with selenium?
- Performance, load, stress testing, manual ad hoc testing, (These tests are done by experts trained in these tools)
- Pure database testing (if we only test the DB itself),
- Unit tests…, look and feel based testing (color, shapes, etc.),
- static testing
- What is in the Selenium tool set?
- Selenium IDE à implemented as a Chrome and Firefox extension, and allows you to record, edit, and debug tests.
- Selenium RC à to write automated web application UI tests in any programming language
- Selenium WebDriverà execute your tests against different browsers
- Selenium GRID à run your tests on different machines against different browsers in parallel.
- What version of Selenium do you use right now?
- JDK (JAVA) - 1.8 à I like it because of à Lambda exp. and, Try catch error handling you may add multiple catches.
- IntelliJ - 2018.03.04
- Selenium - 3.141.59
- TestNG - 6.14.3
- Cucumber – 4.2.6
- Maven - 3.6.0
- GIT - 2.17.2
- Implicit Wait vs Explicit Wait?
- Implicit wait is a wait which waits for a specified time while locating an element before throwing
“NoSuchElementException”. As by default selenium tries to find elements immediately without any wait. So, it is good
to use implicit wait. This wait applied to all elements of the current driver instance. - Explicit wait is a wait which is applied to a particular webelement until the ExpectedCondition specified is met.
- Implicit wait is simply; if condition is met before the timeout, it will continue to next step, if condition is not met within
timeout throw “No Such Element” exception. - Explicit wait sometimes we need to wait for a certain event/condition such as element is visible, clickable, enabled….
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
webDriverWait wait = new WebDriverWait (driver, 5);
wait.until (ExpectedConditions.visibilityOf(element);
- What is fluentWait?
- Let’s say you have an element which sometime appears in just 1 second and some time it takes minutes to appear. In that
case it is better to use fluent wait, as this will try to find element again and again until it find it or until the final timer runs
out. Example is AJAX or JQuery - Subtype of explicit wait but you can override the conditions
Wait<WebDriver>wait=new
FluentWait<Webdriver>(driver).withTimout(5,timeUnit.seconds).pollingEvery(100,timeunit.
milliseconds).ignoring(NoSuchElementException.class);</Webdriver></WebDriver>
- What are various ways of locating an element in Selenium?
- Selenium Locators à Id & name
- In selenium locator is a means of finding an element in the html :
- Id, name, className, xpath, css, linkText, partialLinkText, tagName
- Why I cannot find element?
- Locator changed
- There is an iframe
- Waiting time:: page is loading slowly or Element is dynamic:: locator
- Page is not fully loaded/opened
- Page changes and that element does not exist anymore
- How to highlight an element?
- Selenium WebDriver doesn’t have highlight action.
- But we can use JavaScript to do it
JavascriptExecutor js = ((JavascriptExecutor) driver);
String bgcolor = element.getCssValue(“backgroundColor”);
for(inti=0;i< 10;i++){
changeColor(“rgb(0,200,0)”,
element,driver);//1
changeColor(bgcolor,
element,driver);//2
}
- What is Xpath?
- Xpath is used to find the location of any element on a webpage using html structure.
- We could navigate through elements and attributes in an XML document to locate web Elements such as textbox.
- button. checkbox, Image ext… in web Page
- Absolute (/) and Relative (//) Xpath?
- Syntax à //tagname[@attribute=
value
] - Absolute xpath starts with single slash ( / ), starting from root element and all the way to the element.
- Relative xpath starts with double slash ( // ), starting selection matching anywhere in the document.
- How do you handle dynamic elements?
- Find the static part of the id and write a locator(xpath or css) à And then use Startswith, contains, EndsWith
- contains( ) à //*[contains(@name=
btn
)] - startwith( ) à //label[startwith(@id,
message
)] - text( ) à //td[text() =
usedId
] - or & and à //input[@type =
submit
AND @name =login
]
- How to test dynamic web page?
- There is no one size fits all solution to this problem. We have to understand the application very well
- o Use explicit waits where necessary.
- o Use custom xpaths and css locators
- § Xpath: contains, starts with, ends with, contains text.
- § By finding the element in relation to another stable element using parent, child, sibling relationships
- How to test dynamic table?
- Use custom xpaths and css locators
- o Xpath: contains, starts with, ends with, contains text.
- o By finding the element in relation to another stable element using parent, child, sibling relationships
- I have utility methods that work with table. I have method that takes a table webelement and returns all the column
- names. I have a method that takes a table, number and returns all the data in that row.
- How can we move to parent element using xpath?
- Using (..) expression in xpath, we can move to parent element
- Difference between close() and quit() command?
- driver.close() à used to close the current browser
- driver.quit() à used to close all the browser instances
- How can we move to nth child element using xpath?
- There are two ways:
- o using square brackets with index position
- For ex: div[2] will find th* There are two ways:
- o using square brackets with index position
- For ex: div[2] will find the second div element
- o using position ( ) method
- For ex: div[position()=2] will find the second div elemente second div element
- o using position ( ) method
- For ex: div[position()=2] will find the second div element
- Difference between xpath and css selector?
- with xpath, we can search elements backward or forward…
while css works only in forward direction - Xpath can work with text, css cannot work
- Xpath has more combination and can search by index
css cannot search by index, but css is working faster than xpath.
- What is framework?
- In test automation, framework is the blueprint of test automation.
- It includes your folder structures, where to save you function library, test results, test data, resources.
- It is essential because when you are working on a automation project everyone will have a guideline to follow and our
script will be easier to maintain.
- Talking about HTML reporting during the interview?
- I use multiple methods of reporting in my framework, driver script writes pass/fail to the test cases excel sheet,
- Reporter utility object writes to UFT report, also I have developed a custom HTML reporting engine.
- It sends HTML code to the Notepad and creates a nice HTML report document that nontechnical people can easily
- understand and use.
- How to maximize a web page?
driver.manage().window().maximize();
- In some cases, maximize() will not work > so what will be the way around?
- Actions or change version.
ChromeOptions options = new ChromeOptions();
options.addArguments(“startmaximized”);
- What is the key class in Selenium?
- Gives us option for pressing keys from keyboard
- Key.ENTER
- MUST BE PASSED TO SendKeys() method
- Ex; .sendkeys(“charger” + keys.ENTER)
- What if there is a dynamic popup that comes up randomly
- Use try/catch with alert
- What is Thread.sleep()?
- Slows down selenium to catch up
- Throws exception so must handle it or throw it
- What is Selenium Framework?
- It is a code structure that helps to make code maintenance easy, code readability and code reuse.
- There are mainly 3 type of frameworks created by Selenium WebDriver to automate test cases:
Data Driven Framework
* It is one of the most popular automation frameworks in the market
* All of our test data is generated from some external files;
o excel
o or scenario outline in feature file
o or TestNG Data Provider
* Selenium WebDriver is a great tool to automate web-based applications. But it does not support read and write
operations on excel files. Therefore, we use third party APIs like Apache POI
Keyword Driven Framework
* Keyword driven testing is a scripting technique that uses data files to contain the keywords related to the application
being tested.
* Keywords are written in some external files like excel file and Java code will call this file and execute test cases.
HybridDriven Framework
* A combination of the DDF and KDF is commonly said to be HDF.
* Both the test data and test action are kept in external files.
- How did you use overloaded Methods in Selenium?
- When asserting if two values are equal, I use à Assert.assertEquals(actual, Expected) from TestNG
- You can put in the parameters String, Objects, int, boolean values
- Why we get NoSuchElementException?
- Check if locator is correct
- Check if timing is correct
- Check if element is hidden inside an iframe
- How you handle js alerts?
- If the alert on the browser comes from JavaScript, we use the Alert class.
Alert alert = driver.switchTo.alert();
alert.accept();
alert.dismiss();
alert.sendKeys();
alert.getText()
- How to handle multiple frames?
- If there are 4 frames, you have to go through each from consecutively to reach certain frame. Can’t jump to the 3rd frame
from 1st frame.
- What is the difference between driver.get() and driver.navigateto() ?
- driver.get() -> To open an URL and it will wait till the whole page gets loaded
- driver.navigateto() -> To navigate to an URL and it will not wait till the whole page get loaded
- How to handle frames in Selenium?
- Frames used to embed a html page into another
- Steps
- o Locate the iframe
- o Switch to another iframe with driver.switchTo().frame();
- .frame() -> takes string, Integer, webElement, name or id directly as parameter
- driver.switchTo().frame(webElement);
- driver.switchTo().frame();
- Now you are in the 2nd frame, if you want to find an element outside of the 2nd frame (that you’re currently on)
- throws NosuchElementException
- If you need to switch back to previous frame
- o driver.switchTo().parentFrame() -> Goes one level up
- o driver.switchTo().defaultcontent() -> Goes to the very top
- Can switch using count
- o driver.switchTo(0) -> Counts anything that is not the default frame
- These methods might give you different results based on what browser you are using
- How you handle browser pop ups?
- void dismiss() -> clicks on the “Cancel” button as soon as the pop-up window appears.
- void accept() ->clicks on the “Ok” button as soon as the pop-up window appears.
- String getText() -> returns the text displayed on the alert box.
- void sendKeys(String stringToSend)-> enters the specified string pattern into the alert box.
- How you handle windows/ OS pop ups?
- Selenium doesn’t support windows-based apps, it is an automation testing tool that supports only web application testing.
- We could handle windows-based popups in Selenium using some third-party tools such as AutoIT, Robot class
- driver.getWindowHandle(); This will handle the current window that uniquely identifies it within this driver instance.
- driver.getWindowHandles(); To handle all opened windows
- How to handle Headless browser
- Headless browser: browser that does not open, it runs as a background service / program.
- Example is htmlunitdriver from selenium
o WebDriver = new htmlunitdriver()
o Not very stable - Phantonjsbrowser
o More stable
o browser = new phantomjsbrowser()
- findElement vs findElements?
*!FindElement > this method returns first WebElement !
* gives Exception if the element not found
*! FindElements > returns List <WebElement>;
* does not give Exception if the element not found as a result list has null values</WebElement>
- How to handle multiple windows/tabs?
- Selenium stays on one window
- If you open a window and then 5 tabs popped open, selenium is focused on the first window
- If you are on a new window and you tell selenium to print an element on the default window, it will still work even that user’s focus is on the new window
- Must switch to new window
- Use windowHandle()
- Driver.getWindowHandle()
- Everytime Selenium opens a browser, it’s going to give an index ID for the page called Handles
- Returns the handle/id of current page (as a string)
- driver.switchTo().window(string handle)
- Returns a Set of window handles
- Switch using titles
for(string handle: driver.getWindowHandles()){
driver.switchTo().Window(handle)
if(driver.getTitle().equals(targetTitle){
break;
}
}
- How to find all links in the page?
List<WebElement> list = driver.findElements(By.tagName(“a”));</WebElement>
- Difference between isDisplayed(), isEnabled(). And is Selected() method in selenium WebDriver?
- isDispalyed() -> verify the presence of a web element within the web page. If found à true, If not found à false
- isDisplayed() -> check for the presence of all kinds of web elements available
- isEnabled() ->verify if the web element is enabled or disabled within the web page.
- isEnabled() -> is primarily used with buttons
- isSelected() -> verifies if the web element is selected or not
- isSelected() -> used with radio buttons, dropdowns and checkboxes.
- How to Drag And Drop ?
Actions action = new Actions(driver);
action.clickAndHold(driver.findElement(By.id(“item”)))
.moveToElement(driver.findElement(By.id(“destination”)))
.release().build()
.perform();
- For Scroll down:
WebDriver driver = new ChromeDriver(); JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript(“window.scrollBy(0,250)”, “”);
* OR, we can do as follows:
jse.executeScript(“scroll(0, 250);”);
- For Scroll up:
jse.executeScript(“window.scrollBy(0,-250)”, “”); OR, jse.executeScript(“scroll(0,-250);”);
- How to handle cookies?
● In Selenium Webdriver, we can query and interact with cookies with below built-in method:
driver.manage().getCookies(); // Return The List of all Cookies
driver.manage().getCookieNamed(arg0); //Return specific cookie according to name
driver.manage().addCookie(arg0); //Create and add the cookie
driver.manage().deleteCookie(arg0); // Delete specific cookie
driver.manage().deleteCookieNamed(arg0); // Delete specific cookie according Name
driver.manage().deleteAllCookies(); // Delete all cookies
- Why do we need to handle cookies?
● Each cookie is associated with a name, value, domain, path, expiry, and the status of whether it is secure or not. In order
to validate a client, a server parses all of these values in a cookie.
● When Testing a web application using selenium web driver, we may need to create, update or delete a cookie.
● For example, when automating Online Shopping Application, we many need to automate test scenarios like place order,
View Cart, Payment Information, order confirmation, etc.
● If cookies are not stored, we will need to perform login action every time before we execute above listed test scenarios.
This will increase your coding effort and execution time.
● The solution is to store cookies in a File. Later, retrieve the values of cookie from this file and add to it your current browser
session. As a result, you can skip the login steps in every Test Case because your driver session has this information in it.
● The application server now treats your browser session as authenticated and directly takes you to your requested URL.
- Store cookies cookie information
public class cookieRead extends BasePage{
public static void main(String[] args){
driver.get(“http://demo.guru99.com/test/cookie/selenium_aut.php”);
// Input Email id and Password If you are already Register
driver.findElement(By.name(“username”)).sendKeys(“abc123”);
driver.findElement(By.name(“password”)).sendKeys(“123xyz”);
driver.findElement(By.name(“submit”)).click();
File file = new File(“Cookies.data”); // create file to store cookies
try {
file.delete(); // Delete old file if exists
file.createNewFile();
FileWriter fileWrite = new FileWriter(file);
BufferedWriter Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
for(Cookie ck : driver.manage().getCookies()){
Bwrite.write((ck.getName() +”;”+ ck.getValue() +”;”+ ck.getDomain() +”;”+ ck.getPath()
+ “;” + ck.getExpiry() +”;”+ ck.isSecure()));
Bwrite.newLine();
}
Bwrite.flush(); Bwrite.close(); fileWrite.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
- Do you use JavaScriptExecutor?
- This helps me write my own JavaScript. JS has way more control than selenium.
- we can send JS commands to the browser with using this class
JavaScriptExecutor jsExecutor=(JavaScriptExecutor)driver;
o executeScript(); performs the command
o Inside the parameter is where you put JS code - jsExecutor.executeScript(“alert(‘WARNING: This is a useless message’);” à This code will bring up a JS popup
- You can also put 2 parameters is .executeScript(“js code”,element);
o Used for scrolling (selenium is not good with scrolling, you can say a challenge is when I was working on terms
and condition page, where you have to read the page before clicking on continue.
o When I tried using selenium and actions class it didn’t work, so i used javaexecutor ) and clicking an element;
- Selenium is a suite of tools for automated web testing. It is composed of;
*Selenium IDE(Integrated Development Environment); a Firefox plugin that works for recording and playing back. - Selenium RC(Remote Control) (1.0) ; is a test tool and is used to work on JS to automate the web application. (2004)
- WebDriver (2.0); is a web automation framework and allows you to execute your tests in different browsers. (2011)
- Selenium Grid; allows tests to run in parallel across multiple machines.
- What is Selenium and what is composed of?
- Selenium is open source and free to use without any licensing cost
- It supports multiple languages like Java, Ruby, Python, C#…
- It supports multi-browser testing
- It has a good amount of resources and helping community
- It supports many operating systems like Windows, Mac, Linux …
- Interact with the web application
- What are the advantages of Selenium?