Selenium Flashcards

1
Q

How many changes do you need to make to manage your Selenium scripts? How do you maintain your test scripts and how frequently do you have to modify them?

A

It all depends on the types of changes. As an example, in our Page Object Model (POM) design, if a web element changes, we only update that specific element in its page class but, if there’s a change in existing functionality, we update the relevant functions. When we find new changes leading to test failures, then we update our test scripts.

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

What have you done to improve the performance of the selenium framework?

A

We created reusable elements, wrote efficient functions with clear steps, followed coding standards, wrote locators to handle dynamic elements, and provided data in external files such as Excel, Text files, and property files.

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

What is Selenium? Why do you prefer the Selenium Automation Tool? What are the common test automation tools? What are the testing types that can be supported by Selenium? Challenges, issues and limitations of Selenium?

A

Selenium is a set of open-source tools for automating web browsers, commonly used for functional and regression test automation across different operating systems (Windows, Linux, Macintosh). It supports various browsers like Mozilla Firefox, Internet Explorer, Google Chrome, Safari, and Opera. Selenium also provides compatibility with multiple programming languages, including Java, C#, Python, Perl, Ruby, PHP, and JavaScript. While Selenium and QTP are widely used, there are scenarios where Selenium WebDriver may not be suitable, including challenges in automating Captcha, reading barcodes, handling Windows-based pop-ups, image validation and comparison, and PDF validation and comparison

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
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 is a Firefox plugin, Selenium RC (Selenium 1) is Selenium Remote Control, Selenium WebDriver (Selenium 2) is a browser automation framework using browser-specific drivers, and Selenium Grid is a tool for parallel test execution on multiple platforms. The advantages of Selenium Grid include the ability to run test cases in parallel, conduct multi-browser testing, and execute test cases on multiple platforms concurrently. Currently using Selenium 3.0 due to compatibility, a Maven project aids in easily updating dependencies through the pom.xml file.

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

What are the types of WebDriver APIs available in Selenium? Which WebDriver implementation claims to be the fastest? What is the super interface of WebDriver? What is a headless browser?

A

The webdriver APIs in Selenium include Gecko Driver, InternetExplorer Driver, Chrome Driver, Safari Driver, HTMLUnit Driver. HTMLUnitDriver fastest because it is headless browser which have less User Interface, the Super interface of WebDriver is SearchContext Interface.

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

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

A

There are eight locators in Selenium for identifying WebElements on a webpage: ID, ClassName, Name, TagName, LinkText, PartialLinkText, XPath, and CSS Selector. The choice of locator preference depends on the specific requirements and characteristics of the project.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
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 a tool in Selenium for locating elements, offering two types: Absolute XPath, using a single slash “/”, starting from the document node, and Relative XPath, using double slashes “//,” beginning selection from anywhere within the document. For example, an Absolute XPath could be “/html/body/td/tr/div[1]/div[2],” while a Relative XPath might be “//input[@id=’username’].”

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

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

A

// set the property for chrome driver, specify its location via the webdriver.chrome.driver -> System.setProperty(“we driv-er.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”);  To launch a Chrome browser with Selenium WebDriver, this code sets the ChromeDriver’s location, creates a ChromeDriver instance, and navigates to “http://google.com”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
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 valuable in Selenium automation. CSS selectors are often better for Internet Explorer, while XPath is generally preferred for other browsers like Firefox, Chrome, and Safari. Differences: CSS is generally more user-friendly and readable than XPath. CSS operates only in a forward direction, while XPath allows searching elements backward or forward. XPath can work with text, a capability not present in CSS. In terms of speed, CSS and XPath are generally comparable, but CSS is often noticeably faster than XPath in Internet Explorer, based on practical experiences.

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

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

A

To open a URL in Selenium WebDriver, we can use either driver.get(url) or driver.navigate().to(url). The difference is driver.get(url) directly opens the URL and waits for the page to load, but driver.navigate().to(url) provides more navigation control without waiting for the page to load immediately.

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

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

A

close() - It is used to close the browser or page which is currently having the focus. quit() - It is used to shut down the web driver instance or destroy the webdriver instance (Close all the windows).

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

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

A

To get the text of a web element using Selenium WebDriver, we can use the getText() method, and to retrieve the value of an attribute, or we can use the getAttribute(attributeName) method. String buttonText =driver.findElement(By.cssSelector(“div.success”)).getText();StringinnerText=driver.findElement(By.cssSelector(“div.success”)).getAttribute(“type”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
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 an 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
14
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 types. Also when there is a group of Radio Buttons/Check Boxes on the page then, their names may be 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
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. Every time 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(); getWindowHan-dles() method or command returns all handles from all opened browsers by Selenium WebDriver during execution Set<String> handleSet = driver.getWindowHandles(); //Returns a set of window handles You can use SwitchTo().Window("handle") to switch to the window you desire. You can use Switch-To().Window("mywindowID"), if you know the window ID. SwitchTo().Window("") will always go back to the base/main window. Method to switch to a window based on title public switchToWindow(String titleName) { driv-er.switchTo().window(titleName); //titleName = windowName }</String>

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

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

A

We can use the Select class to interact with dropdowns in Selenium WebDriver, providing methods such as selectByVisibleText(), selectByIndex(), and selectByValue() for different selection options. Additionally, the isMultiple() method helps verify if the dropdown allows multiple selections, allowing conditional handling based on its behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
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”)); driv-er.switchTo().frame(iframeElement); 3. Switch to Frames by Index driver.switchTo().frame(0)

18
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 an alert? How do you send a text to alert? How can we handle Windows-based pop-ups?

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 driv-er.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(); ordriver.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.

19
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 “TimeOutEx-ception” exception. driv-er.manage().timeouts().implicitlyWait(TimeOut, TimeU-nit.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 “ElementNotVisibleEx-ception” exception. The explicit wait is an intelligent kind of wait, but it can be applied only for specified elements. WebDriverWait wait = new WebDriverWait(driver, 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 “ElementNotVisibleExcep-tion” 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);

20
Q

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

A

By using Thread.sleep(5000);

21
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 = driv-er.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

22
Q

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

A

First, store that element in an 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);

23
Q

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

A

We use JavascriptExecutor // Scroll Up on application using Selenium JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“window.scrollBy(0,250)”); // 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);

23
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 JavascriptExecu-tor je = (JavascriptExecutor)driver; je.executeScript(“document.getElementById(‘email’).value=’your@email.com’;”);

24
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);

25
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.

26
Q

How to capture a 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

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 because 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. An 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: We 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

27
Q

What are the different exceptions you have faced in Selenium WebDriver? What is StaleElementReferenceException? Have you encountered it and how did you handle 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”)));

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 and 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 initialization. Chrome , IE and Firefox testing using Webdriver. In our property file we store keys for the browser and every time 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 upload-Element.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 than 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

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

A

Page Object Model (POM) is test design pattern, helps to organize page objects based on pages, making it easy to differentiate between scripts and page objects. Page Factory is way of implementing the Page Object Model and is built into Selenium. In standard POM, we use ‘By’ to define locators, while in Page Factory, we utilize the @FindBy annotation to define page objects. The Page Object Model is a design approach, and PageFactory is class that provides implementation for this design.

33
Q

What is the difference between POM and PageFactory?

A

The Page Object Model (POM) is a design pattern that helps organize scripts and page objects. Page Factory in Selenium is one implementation of the POM design approach. In POM, locators use ‘By,’ but in Page Factory, the @FindBy annotation is used to define page objects. In POM, each page object needs to be individually initialized, which can sometimes lead to errors. However, Page Factory updates this process through the initElements() method, automatically initializing all page objects without errors.

34
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 cannot check the image using selenium.

35
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

35
Q

Scenario: you have 2 frames on the page and in one of them you need to enter some text, and in the second one you need to click on 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 driv-er.switchTo().defaultContent(); again I will switch to second frame driver.switchTo().frame(2); and click on button

36
Q

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

A

WebElement cellIneed = tableRow.findElement(By.xpath(“//table/tbody/tr[2]/td[3]”));

37
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

We 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 = driv-er.findElements(By.xpath("//table[@summary='Sample Table']/tbody/tr")); for (int i=rows.size()-1; i>=0; i--) { String latRowValue = rows.get(i).getText(); Sys-tem.out.println(latRowValue); break; }</WebElement></WebElement>