Monday, August 26, 2024

JavaScript Executor in Selenium with Java MCQ

 MCQs on JavaScript Executor in Selenium with Java

What is the purpose of the JavaScriptExecutor in Selenium WebDriver?


a) To execute SQL queries

b) To execute JavaScript commands in the context of the browser

c) To manage browser cookies

d) To handle browser pop-ups

Answer: b) To execute JavaScript commands in the context of the browser


Which interface must be implemented to use JavaScriptExecutor in Selenium?


a) WebDriver

b) TakesScreenshot

c) JavascriptExecutor

d) WebElement

Answer: c) JavascriptExecutor


How do you cast a WebDriver instance to use JavaScriptExecutor in Selenium Java?


a) JavascriptExecutor js = (JavascriptExecutor) driver;

b) JavaScriptExecutor js = (JavaScriptExecutor) driver;

c) jsExecutor js = (jsExecutor) driver;

d) ScriptExecutor js = (ScriptExecutor) driver;

Answer: a) JavascriptExecutor js = (JavascriptExecutor) driver;


Which method is used to execute JavaScript commands using JavaScriptExecutor?


a) runScript(String script)

b) executeScript(String script)

c) performScript(String script)

d) executeJavaScript(String script)

Answer: b) executeScript(String script)


What is the correct JavaScriptExecutor syntax to scroll to the bottom of the page?


a) js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

b) js.executeScript("window.scrollToBottom()");

c) js.executeScript("scroll(0, end)");

d) js.executeScript("document.scrollTo(0, document.body.scrollHeight)");

Answer: a) js.executeScript("window.scrollTo(0, document.body.scrollHeight)");


Which JavaScriptExecutor method is used to click an element that is not interactable by WebDriver's click() method?


a) executeClick()

b) performClick()

c) executeScript("arguments[0].click();", element);

d) element.clickUsingJS()

Answer: c) executeScript("arguments[0].click();", element);


How can you retrieve the inner text of an element using JavaScriptExecutor?


a) js.executeScript("return arguments[0].innerText;", element);

b) js.executeScript("getText(arguments[0]);", element);

c) js.executeScript("arguments[0].getText();", element);

d) js.executeScript("getInnerText(arguments[0]);", element);

Answer: a) js.executeScript("return arguments[0].innerText;", element);


Which of the following JavaScriptExecutor methods scrolls the page until a specified element is in view?


a) js.executeScript("window.scrollIntoView(arguments[0]);", element);

b) js.executeScript("arguments[0].scrollIntoView();", element);

c) js.executeScript("scrollToView(arguments[0]);", element);

d) js.executeScript("scrollElementIntoView(arguments[0]);", element);

Answer: b) js.executeScript("arguments[0].scrollIntoView();", element);


How would you highlight a web element using JavaScriptExecutor?


a) js.executeScript("arguments[0].highlight();", element);

b) js.executeScript("arguments[0].style.border='3px solid red'", element);

c) js.executeScript("highlight(arguments[0]);", element);

d) js.executeScript("arguments[0].setBorder('red');", element);

Answer: b) js.executeScript("arguments[0].style.border='3px solid red'", element);


What is the output type of the executeScript method when used to return the title of the current webpage?


a) String

b) WebElement

c) Object

d) void

Answer: a) String


Which JavaScriptExecutor method would you use to retrieve the current URL of the webpage?

a) js.executeScript("return window.location.href");

b) js.executeScript("getCurrentUrl();");

c) js.executeScript("return document.URL;");

d) Both a) and c)

Answer: d) Both a) and c)


In Selenium, which method allows you to set the value of an input field using JavaScriptExecutor?

a) js.executeScript("arguments[0].setValue('value');", element);

b) js.executeScript("arguments[0].value='new value';", element);

c) js.executeScript("arguments[0].setAttribute('value', 'new value');", element);

d) js.executeScript("setValue(arguments[0], 'new value');", element);

Answer: b) js.executeScript("arguments[0].value='new value';", element);


How can JavaScriptExecutor help in handling the "Element is not clickable at point" exception in Selenium?

a) By scrolling the element into view before clicking

b) By using Actions class

c) By refreshing the browser

d) By resizing the browser window

Answer: a) By scrolling the element into view before clicking


How would you use JavaScriptExecutor to get the current window height?

a) js.executeScript("return window.height;");

b) js.executeScript("return window.innerHeight;");

c) js.executeScript("return document.body.clientHeight;");

d) js.executeScript("return window.clientHeight;");

Answer: b) js.executeScript("return window.innerHeight;");


Which JavaScript command executed by JavaScriptExecutor disables a text field in a webpage?

a) js.executeScript("arguments[0].disable = true;", element);

b) js.executeScript("arguments[0].disabled = true;", element);

c) js.executeScript("arguments[0].setAttribute('disabled', 'true');", element);

d) Both b) and c)

Answer: d) Both b) and c)


What is a potential drawback of using JavaScriptExecutor in Selenium scripts?

a) It can only be used with Firefox

b) JavaScript execution can be slower than WebDriver methods

c) It can cause security issues if not used carefully

d) JavaScriptExecutor is not supported in Selenium

Answer: c) It can cause security issues if not used carefully


When would you prefer using JavaScriptExecutor over standard WebDriver methods?

a) When interacting with elements that are hidden or not visible

b) When you want to handle browser cookies

c) When executing JavaScript alerts

d) When managing multiple browser tabs

Answer: a) When interacting with elements that are hidden or not visible


Which JavaScriptExecutor method is best for checking the loading status of a webpage?

a) js.executeScript("return document.readyState;");

b) js.executeScript("document.loadComplete();");

c) js.executeScript("window.pageLoad();");

d) js.executeScript("document.pageLoaded;");

Answer: a) js.executeScript("return document.readyState;");


How can you use JavaScriptExecutor to dynamically change the style of an element in Selenium?

a) js.executeScript("arguments[0].style='color:red';", element);

b) js.executeScript("arguments[0].setStyle('color', 'red');", element);

c) js.executeScript("arguments[0].style.color='red';", element);

d) js.executeScript("setColor(arguments[0], 'red');", element);

Answer: c) js.executeScript("arguments[0].style.color='red';", element);


How can JavaScriptExecutor be used to handle the page scrolling functionality?

a) js.executeScript("window.scrollBy(0,500)");

b) js.executeScript("scrollPageBy(0,500);");

c) js.executeScript("pageScroll(0,500);");

d) js.executeScript("scrollWindow(0,500);");

Answer: a) js.executeScript("window.scrollBy(0,500)");

Capturing Screenshots of the Page Using Selenium Java MCQ

 MCQs on Capturing Screenshots of the Page Using Selenium Java

Which Selenium interface is primarily used to capture a screenshot in Java?

a) TakesScreenshot

b) ScreenshotCapture

c) ImageCapture

d) CaptureScreen

Answer: a) TakesScreenshot

Which method is used to take a screenshot in Selenium WebDriver?

a) getScreenshot()

b) captureScreen()

c) getScreenshotAs()

d) takeScreenshot()

Answer: c) getScreenshotAs()


What is the return type of the getScreenshotAs() method?


a) String

b) File

c) BufferedImage

d) WebElement

Answer: b) File


In Selenium, which OutputType is used to get a screenshot as a file?


a) OutputType.STRING

b) OutputType.FILE

c) OutputType.BYTES

d) OutputType.PNG

Answer: b) OutputType.FILE


What is the correct way to capture a screenshot and store it as a file in Java using Selenium?


a) File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

b) File scrFile = driver.getScreenshotAs(OutputType.FILE);

c) File scrFile = driver.captureScreen(OutputType.FILE);

d) File scrFile = driver.takeScreenshotAs(OutputType.FILE);

Answer: a) File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);


How do you save a captured screenshot to a specific location in your file system?


a) Files.copy(scrFile, new File("path/to/save/screenshot.png"));

b) scrFile.copyTo("path/to/save/screenshot.png");

c) scrFile.saveAs("path/to/save/screenshot.png");

d) Files.copy(scrFile, "path/to/save/screenshot.png");

Answer: a) 


When capturing a screenshot in Selenium, which exception must be handled or declared to be thrown?


a) NullPointerException

b) IOException

c) ElementNotVisibleException

d) NoSuchWindowException

Answer: b) IOException


Which Selenium method would you use to capture a screenshot and return it as a byte array?


a) driver.getScreenshotAs(OutputType.FILE)

b) driver.getScreenshotAs(OutputType.BYTES)

c) driver.takeScreenshot(OutputType.BYTES)

d) driver.getBytesScreenshot()

Answer: b) driver.getScreenshotAs(OutputType.BYTES)


Which library can be integrated with Selenium for advanced screenshot functionalities, like capturing full-page screenshots?


a) SikuliX

b) Ashot

c) TestNG

d) Junit

Answer: b) Ashot


How can screenshots be embedded into test reports in Selenium using TestNG?

a) Use the Reporter.log() method with a screenshot path

b) Use System.out.println() with a screenshot path

c) Use FileUtils to print the screenshot to the console

d) Use Files.save() method to add screenshots to the HTML report

Answer: a) Use the Reporter.log() method with a screenshot path


In Selenium, which of the following statements is not a best practice when capturing screenshots?

a) Capturing screenshots on every step

b) Capturing screenshots only on test failures

c) Capturing screenshots at key points during a test

d) Saving screenshots with meaningful names

Answer: a) Capturing screenshots on every step


How do you handle a WebDriverException thrown when trying to take a screenshot in Selenium?

a) Catch the exception and log an error message

b) Ignore the exception

c) Use try-catch and retry taking the screenshot

d) Refresh the browser and try again

Answer: a) Catch the exception and log an error message


What Selenium WebDriver functionality is required to capture screenshots in a headless browser?

a) TakesScreenshot interface

b) ScreenshotCapture utility

c) File class for saving

d) WebDriverScreenshot()

Answer: a) TakesScreenshot interface


How can you ensure the screenshots are saved in a specific directory dynamically during runtime?

a) Use a hard-coded path

b) Use System.getProperty("user.dir") to dynamically set the path

c) Use System.getScreenshotDirectory()

d) Manually create directories every time before running the test

Answer: b) Use System.getProperty("user.dir") to dynamically set the path


What is the advantage of using Base64 encoded screenshots in Selenium?

a) Screenshots are saved in a text format

b) Screenshots are more secure

c) Screenshots can be easily embedded in HTML reports without saving as a file

d) Screenshots are automatically compressed

Answer: c) Screenshots can be easily embedded in HTML reports without saving as a file


Which output type is most suitable for storing a screenshot directly in a database?

a) OutputType.FILE

b) OutputType.BASE64

c) OutputType.STRING

d) OutputType.BYTES

Answer: d) OutputType.BYTES


How can you handle the NotSupportedException when taking screenshots in Selenium?

a) Ensure the WebDriver instance is cast to TakesScreenshot

b) Update the browser

c) Ignore the exception

d) Install additional plugins for Selenium

Answer: a) Ensure the WebDriver instance is cast to TakesScreenshot


What is the best practice for naming screenshot files in Selenium automation tests?

a) Using a generic name like screenshot.png

b) Including the test case name and timestamp in the file name

c) Using random names generated by the system

d) Overwriting the same file for each screenshot

Answer: b) Including the test case name and timestamp in the file name

Webdriver and Methods

Webdriver(I):

Webdriver (I) -  is predefined interface in Selenium.

-   represents any type of browser

                  -- chrome browser

                             Edge

                            ff

                           IE 

- Predefined methods can be used to control browser common operations like

Common Operations:

·        Open URL: Load a web page URL in the browser.

·        Close Browser: Close the current browser window.

·        Quit: Close all browser windows and safely end the WebDriver session.

·        Locate Elements: Find and interact with elements on a web page.

·        Find Multiple Elements: Locate multiple elements matching a specified selector on a web page

     

Important Methods in WebDriver Interface:

The WebDriver interface in Selenium provides essential methods for automating interactions with web browsers. Here’s an overview of some key methods:

Refer API doc:

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebDriver.html

1. get(String url):

  • Purpose: Opens the specified URL in the current browser window.
  • Usage: driver.get("https://www.example.com");
  • Example: Loads the webpage located at "https://www.example.com".

2. getTitle():

  • Purpose: Retrieves the title of the current web page.
  • Usage: String title = driver.getTitle();
  • Example: Retrieves the title of the currently open browser tab.

3. getCurrentUrl():

  • Purpose: Retrieves the URL of the current web page.
  • Usage: String currentUrl = driver.getCurrentUrl();
  • Example: Returns the URL currently displayed in the browser.

4. getPageSource():

  • Purpose: Retrieves the HTML source code of the current web page.
  • Usage: String pageSource = driver.getPageSource();
  • Example: Fetches the entire HTML content of the currently open page.

5. navigate().to(String url):

  • Purpose: Navigates the browser to the specified URL.
  • Usage: driver.navigate().to("https://www.example.com");
  • Example: Similar to get(String url), but can be used for navigation chaining.

6. close():

  • Purpose: Closes the current browser window that is currently focused.
  • Usage: driver.close();
  • Example: Closes the active browser tab or window.

7. quit():

  • Purpose: Closes all browser windows and ends the WebDriver session.
  • Usage: driver.quit();
  • Example: Terminates all browser instances opened by Selenium WebDriver.

quit(): to close all browser windows which are opened by Selenium

            ex:  if Selenium code opens 3  or 4 browser windows, quit() -can be used close all browser windows

8. findElement(By by):  can be used to find the element in page using By class locators

                                        to identify the element in page

                                        to locate the element in page

  Usage: WebElement element = driver.findElement(By.id("elementId"));

  Example: Finds the HTML element identified by its id attribute.

9. findelements(By by):  to find the list of elements  in page using By class locators

                        locate

                     identify

  Usage: List<WebElement> elements = driver.findElements(By.className("className"));

  Example: Retrieves a list of HTML elements identified by their className attribute.

getWindowHandle()  --> Later

getWindowHandles() --> Later

code:

package SeleniumBasics1;

import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserBasicsMethods1 {

            public static void main(String[] args) throws InterruptedException {

                       

                        //open chrome browser

//                     2 steps

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        ChromeDriver driver =  new ChromeDriver();

                       

                        // we can store Chromdriver class obj reference in webdriver interface var

                        //  driver  - refers chrome browser

                        //    Edgedriver

                        // firefoxdriver

                        // to open the url in chrome browser --> get("url")

                        //https://www.amazon.com/

                        driver.get("https://www.amazon.com/");

                        //  chrome browser

                        //                     Thread.sleep(3000);

                        // get current url

                        String  currentURL = driver.getCurrentUrl();

                        //                       https://www.amazon.com/

                        //                

                        //    currentURL  = https://www.amazon.com/

                        System.out.println("url=" + currentURL);

                        //

                        // get title of page

                        String getTitle  = driver.getTitle();

                                    //                  Amazon.com

                        //               

                        // getTitle  =  Amazon

                        System.out.println("getTitle="+getTitle);

                        //                      Amazon.com

                        // get page source code of browser page

                        String htmlcode= driver.getPageSource();

                                                            //                     // htmlcode=<html class="a-no-js" lang="en-us"><!--<![endif]--><head>

                                                            ////                  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

                                                            ////                  <meta charset="utf-8">

                                                            ////                  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

                                                            //                     <title dir="ltr">Amazon.com</title>

                        System.out.println("htmlcode="+htmlcode);

                        Thread.sleep(3000);

                        // close()

                        // close the currently focussed browser window

//                     driver.close();

                        //  quit() to close all browser windows which are opened by Selenium

                        driver.quit();

                       

                        // FAQ Difference between  close and quit()

                        //FindElement()

                        // findElements()

                        // getWindowHandle()

                        //                                             getWindowHandles()

 

            }

}

get ()   and Navigate():

package SeleniumBasics1;

import org.openqa.selenium.chrome.ChromeDriver;

public class GetAndNavigateDifference  {

            public static void main(String[] args) throws InterruptedException {

                        //2  create obj for ChromeDriver- Class

                        System.setProperty("webdriver.chrome.driver", ".\\Drivers\\chromedriver.exe");

                        ChromeDriver driver = new ChromeDriver();

                       

                        // open some url in browser-https://www.amazon.com/

                        driver.get("https://www.amazon.com/");

                        //  get()  it waits till it loads all elements in the page  , then only it goes to next stmt

                        Thread.sleep(5000);

                        // open https://www.facebook.com/

                        driver.navigate().to("https://www.facebook.com/");

                        // navigate() -  it does not wait till it loads all elements in the page

                        //                                 Thread.sleep(5000);

                        // to navigate to previous page --https://www.amazon.com/

                        driver.navigate().back();

                        Thread.sleep(5000);

                        //  go to next page

                        driver.navigate().forward();

                        //used to navigate to  next page based on browser history

                        //https://www.facebook.com/

                        // Refresh page

                        Thread.sleep(5000);

                        driver.navigate().refresh();

                        // FAQ Difference  get() and Navigate()

            }

}

FindElement( By  by ):

can  find element / locate ele / identify the ele in web page  using By class locators

(by using id, name, class.. etc) and returns 1st matched web ele.

Usage:

  • WebElement element = driver.findElement(By.id("elementId"));

By class Locators :

-------------------

 is predefined class in Selenium

 has some methods to identify the element in web page

           

            Male <input type="radio" name = "male" id = "maleid"  class='firstclass'>

            Female<input type="radio" name= "female" id= "femaleid">

The By class in Selenium provides several methods that return instances of By representing different locator strategies to find elements on a web page:

  • By.id("idValue"): Locates an element by its id attribute.
  • By.name("nameValue"): Locates an element by its name attribute.
  • By.className("classNameValue"): Locates an element by its class attribute.
  • By.xpath("xpathExpression"): Locates an element using an XPath expression (advanced).
  • By.cssSelector("cssSelectorExpression"): Locates an element using a CSS selector (advanced).
  • By.linkText("linkText"): Locates an <a> element by its exact link text.
  • By.partialLinkText("partialLinkText"): Locates an <a> element by partial link text.
  • By.tagName("tagName"): Locates elements by their HTML tag name.

 By.id("id val");   --->  By.id("maleid")   -->  id =   'maleid'

 By.name("name val"); --> By.name("male")  --> name  =male

 By.classname("class value") --> By.className("firstclass") -->  class = firstclass

 

By.xpath("") -- >  By.xpath(" write xpath for desired element")  --> Later classes

By.cssSelector("") - >  By.CssSelector("Write CSS selector path")  -->Later classes

            <a href ="https://www.google.com" > Click My google  <a>

 

By.Linktext("Link text") - Click My google -- > By.linkText("Click My google ")   -->  give full link text

By.partialLinkText(" pass partial link text ") -> Click My google  -- >    -->

            By.partialLinkText("Click")

            By.partialLinkText("My google")

            By.partialLinkText("google")

             

By.tagName(" pass tag name ")  --> By.tagname("p")

                                                By.tagname("input")

                                                By.tagname("a")

                                                By.tagname("select")

 

FAQ Can you tell me locator names ?

HW    open chrome browser  and enter url Facebook.com, get title and get current url and navigate to redbus.com and get title and get current url , close the browser.

HW open chrome browser , enter url - Facebook.com and navigate to redbus.com and get title and get current url,

,  go to previous page, get title, get url ,

 go to next page and get title , get url ?

Refer API Docs:

Search 'downloads Selenium' > Click on offical website  > go to Java section > Click 'API Docs' > it opens API  doc page>  Search for any predefine class or interface i.e Webdirver or ChromeDriver-->  click respective value > it opens 'Webdriver' details    and all Methods.. 

Modifier and Type, Method , Description

https://www.selenium.dev/selenium/docs/api/java/index.html

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebDriver.html

Change log:

-------------------

Refer change log :

https://github.com/SeleniumHQ/selenium/blob/trunk/java/CHANGELOG

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...