The Ultimate List of Selenium Interview Questions

Selenium is a popular open-source web automation testing tool. Here is the comprehensive list of Selenium interview questions and answers.

Selenium Interview questions

Table of Contents

1) What is Selenium?

Selenium is a very popular tool that is used to automate browser-based applications. It is open source and easy to use and supports several programming languages like Java, python, c#, php etc.

2) What is the difference between selenium 3 and selenium 4?

  • Selenium 3 uses the JSON wire protocol and Selenium 4 uses W3C standardization.
  •  Native Support was removed for browsers like Opera and PhantomJs in Selenium 4.
  • Selenium IDE was only available as a Firefox extension in version 3. However, Selenium version 4 IDE is available for Chrome as well.
  • Unlike Selenium 3, Selenium 4 provides native support for Chrome DevTools.
  • Selenium 4 has introduced Relative locators that allow testers to find elements relative to another element in the DOM.

3) What type of locator strategies are available in Selenium?

  1. By Id
driver.findElement(By.id(“userId”));

2. By Name

driver.findElement(By.name(“userName”);

3. By TagName

driver.findElement(By.tagName(“button”)

4. By ClassName

  driver.findElement(By.className("ClassName"));

5. By LinkText

driver.findElement(By.linkText(“Today’s deals”))

6. By Partial Link Text

driver.findElement(By.partialLinkText("here"))

7. By Xpath

driver.findElement(By.xpath("//span[contains(text(),'an account')]"))

8. By Css

driver.findElement(By.cssSelector(“input#email”))

4) What are the changes in the locator strategies in Selenium 4?

Traditional Locators (Selenium 3)

Id, Name, ClassName, TagName, Link text, Partial LinkText, Xpath, CSS Selector.

Relative Locators (Selenium 4)

above, below, Left of, Right Of, Near

Locators can also be chained as per the latest Selenium 4 Release.

By submitLocator = RelativeLocator.with(By.tagName("button")).below(By.id("email"))
                    .toRightOf(By.id("cancel"));

5) What is the CSS locator strategy in Selenium?

CSS locator strategy can be used with Selenium to locate elements, it works using a cascade style sheet location method in which – Direct child is denoted with – (a space) and Relative child is denoted with – >id, class

Example:

css=input[name=’q’]
css=input[id=’lst-ib’] or input#lst-ib
css=input[class=’lst’] or input.lst

6) Which selenium web driver locator should be preferred?

ID is the preferred choice because it is less prone to changes, However, CSS is considered to be faster and is usually easy to read. XPath can walk up and down the DOM, which makes the XPath more customizable.

7) Explain difference between findElement() and find elements().

  • findElement(): This command is used for finding a particular element on a web page, it is used to return an object of the first found element by the locator. Throws NoSuchElementException if the element is not found.
  • find elements(): This command is used for finding all the elements in a web page specified by the locator value. The return type of this method is the list of all the matching web elements present in the DOM. It returns an empty list if no matching element is found.

8) Explain the difference between Thread.Sleep() and selenium.setSpeed().

  • Thread.Sleep(): This method causes the current thread to suspend execution for a specified period.
  • selenium.setSpeed():setSpeed sets a speed that will apply a delay time before every Selenium operation.

9) How to handle stale element reference exceptions in Selenium?

The stale element exception occurs when the element is destroyed and recreated again in DOM. When this happens the reference of the element in the DOM becomes stale. This Exception can be handled in numerous ways.

  1. Refresh the page and try to locate the stale element again.
  2. Use Explicit wait to ignore the stale element exception.
  3. Try to access the element several times in the loop(Usually not recommended.)

10) What are the different types of WebDriver Application Programming Interfaces available in Selenium?

Chrome, Geko Driver, Chromium, Edge.

11) How to open the browser in incognito mode.

This can be done by using the ChromeOptions class to customize the Chrome driver session and adding the argument as “incognito”.

ChromeOptions options = new ChromeOptions(); options.addArguments("--incognito"); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, options);

12) How many parameters Selenium required?

Selenium requires four parameters:

  • Host
  • Port Number
  • Browser
  • URL

13) How to retrieve CSS properties of an element.

driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”); 

14) How can you use the Recovery Scenario in Selenium WebDriver?

By using “Try Catch Block” within Selenium WebDriver Java tests.

15) How To Highlight Element Using Selenium WebDriver?

Use Javascript Executor interface:

JavascriptExecutor js = (JavascriptExecutor) driver;
 js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element); 

16) Explain a few advantages of the Page Object Model.

  • Readable and Maintainable code.
  • Less and optimized code.
  • Low redundancy.

17) List some Commonly used interfaces of selenium web driver.

  • WebDriver
  • TakesScreenshot
  • JavascriptExecutor
  • WebElement
  • SearchContext

18) What is the difference between @FindAll and @Findbys.

@FindBys: When the required WebElement objects need to match all of the given criteria use @FindBys annotation.

<span class="hljs-meta">@FindBys( {
   @FindBy(className = "class1")
   @FindBy(className = "class2")
} )private List <WebElement> ele //elements With Both_class1 AND class2;</span>

@FindAll: When required WebElement objects need to match at least one of the given criteria using the @FindAll annotation.

<span class="hljs-meta">@FindAll({
   @FindBy(className = "class1")
   @FindBy(className = "class2")
})private List<WebElement> ele //elements With Either_class1 OR class2 ;

19) How to Click on a web element if the selenium click() command is not working.

There are multiple ways provided by the Selenium web driver to perform click operations. We can use either the Action class or the JavaScript executor interface.

a) Javascript executor is an interface provided by selenium to run javascript through selenium web driver.

import org.openqa.selenium.JavascriptExecutor;
public void clickThruJS(WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) Driver;
executor.executeScript(“arguments[0].click();”, element);
}

b) Action class is provided by Selenium to handle mouse and keyboard interactions.

import org.openqa.selenium.interactions.Actions;
public void ClickToElement(WebElement elementName) {
 Actions actions = new Actions(Driver);
 actions.moveToElement(elementName).perform();
 actions.moveToElement(elementName).click().perform();
 }

20) Explain some common Selenium exceptions.

Here is the list of some common selenium exceptions.

1)ConnectionClosedException

This exception takes place when the connection between the web driver and the client is lost.

2)UnreachableBrowserException

This exception occurs generally when the server address is invalid or the browser is crashed for some reason.

3)ElementClickInterceptedException

The command was unable to be performed because the element that was requested to be clicked was hidden by the element receiving the events.

4)ElementNotInteractableException

This Selenium exception is raised when a DOM element is displayed but can not be interacted with.

5)ElementNotSelectableException

When an element is displayed in the DOM but is not available for selection, hence is not interactable.

6)InsecureCertificateException

This exception triggers when Navigation makes the user agent hit a certificate warning, which is caused by an invalid or expired TLS certificate.

7)InvalidSwitchToTargetException

This Selenium exception is raised if the frame or window target to be switched does not exist.

8)RemoteDriverServerException

This Selenium exception is raised when a server fails to reply as a result of improperly stated capabilities.

9)TimeoutException

This exception is thrown when there is not enough time for a command to be completed.

10)WebDriverException

This exception takes place when the WebDriver is trying to perform some action right after you close the browser.

21) How to disable Chrome notifications using Selenium?

You need to use Chrome options to disable notifications on Chrome:

Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);

22) What is the difference between getText() and getAttribute().

getText() method returns the text present which is visible on the page by ignoring the leading and trailing spaces, while the getAttribute() method returns the value of the attribute defined in the HTML tag.

23) What are the different ways to reload a webpage in Selenium?

1)Driver.navigate().refresh()
2)Driver.get(Driver.getCurrentUrl())
3)Driver. findElement(By.id(“id”)).sendKeys(Keys.F5);
4)Driver.navigate().to(Driver.getCurrentUrl())

24) Explain build().perform() in actions class.

build() This method in the Actions class is used to create a chain of actions or operations you want to perform.

perform() This method is used to execute a chain of actions that are built using the Action build method.

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

driver. close(): Close the browser window that is currently in focus and make session-id invalid or expired.

driver.quit(): Closes all the browser windows and terminates the web driver session. Session-id becomes null.

26) How to select a value from the Dropdown?

By using Select class. The select class provides methods to select by index, select by value, and select by visible text.

WebElement mySelectElement = driver.findElement(By.name("dropdown"));
Select dropdown = new Select(mySelectElement);
 dropdown.selectByVisibleText(Text);
 dropdown.selectByIndex(Index);
 dropdown.selectByValue(Value);

27) How do select values from the multi-select Dropdown?

The select class has a method named “isMultiple()“. If a dropdown is a multi-select dropdown then this method returns true.

Select multiSelect = new Select(driver.findElement(By.xpath(//*[@id='City']);
 if(multiSelect.isMultiple()){
	//Selecting multiple values by index
	oSel.selectByIndex(1);
	oSel.selectByIndex(2);
 }

28) How to deselect an already selected value?

The select class has methods to deselect values similar to select values. We can use deselectByIndex, DeselectByValue, or DeselectByVisibleText.

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));
//Deselect option with text "Argentina"
select.deselectByVisibleText("Argentina");

29) How to perform scroll operation in Selenium?

By using the JavaScriptExecutor interface scroll operations can be handled.

driver.navigate().to("https://www.automationqahub.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,-250)", "");

30) How to exclude a test method from execution in TestNG.

By adding the exclude tag in the testng.xml file.

<classes> 
  <class name=”TestCaseName”>  
<methods>
  <exclude name=”TestMethodName”/>
</methods>
  </class>
</classes>

31) What are the different ways of ignoring a test from execution?

  • Making parameter “enabled” as “false”.
  • Using the “exclude” parameter in testng.xml.
  • “throw new SkipException()” in the if condition to Skip / Ignore Test.

32) What is the difference between scenario and scenario outline in cucumber?

When we want to execute a test one time then we use the scenario keyword. If we want to execute a test multiple times with different sets of data then we use the scenario outline keyword. A scenario outline is used for data-driven testing or parametrization. We use example keywords to provide data for the scenario outline.

33) What is the difference between @BeforeTest and @BeforeMethod?

@BeforeTest will run only once before each test tag defined in testng.xml, however, @BeforeMethod will run before every method annotated with the @Test tag. In other words, every test in a file is a method but vice versa is not true, so no matter how many methods are annotated with @Test, @BeforeTest will be called only one time and @BeforeMethod executes before each test method.

34) Explain cucumber options with the keywords.

@CucumberOptions enables us to define some settings for our tests, it works like the cucumber JVM command line. Using @CucumberOptions we can define the path of the feature file and the step definition file, we can also use other keywords to set our test execution properly.

35) What is cucumber DryRun?

A dry Run is used to check the complete implementation of all the mentioned steps present in the Feature file. If it is set as true, then Cucumber will check whether every step mentioned in the Feature File has the corresponding code written in the Step Definition file or not.

36) How to set the Priority of cucumber Hooks?

@Before(order = int) : This runs in incremental order, like (order=0) will execute first then (order=1) and so on.

@After(order = int): This executes in decremental order, which means order = 1 would run first and 0 would be after 1.

37) What is a data table in cucumber and how to use it?

Data tables are used when the scenario step requires to be tested with multiple input parameters, multiple rows of data can be passed in the same step and it’s much easier to read.

Scenario: Valid Registration Form Information 
Given User submits a valid registration form
| John | Doe |01-01-1990 |999999999 |
Then System proceeds with registration

38) Explain invocation count in testNg.

  • invocation count: It refers to the number of times a method should be invoked. It will work as a loop. Eg: @Test(invocation count = 7) . Hence, this method will execute 7 times.

39) How to run test scripts in multiple environments?

We can use the switch case to handle the different environments. When the user provides env from the command line like “mvn clean test -Denv=UAT” based on the value script execution will start on that particular environment. If the user forgot to provide the env then configure the @Optional parameter to run scripts on the default environment.

public class BaseWeb 
{
  @Parameters({"env"})
  @BeforeMethod(alwaysRun = true)
  public void beforeTest(@Optional("UAT") final String env) {
        switch (env)
         {
          case "UAT":
                baseUrl = "Url for UAT";
                break;
          case "PROD":
                baseUrl = "Url for PROD";
                break;
          default:
           
      }
    }
}

40) How to read Test data from CSV files in Selenium?

We can use OpenCsv Utility to read CSV files.

Add the below dependency in the pom.xml file.

<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.7.1</version>
</dependency>

Create a class and add the below code.

public class demo {
	
 public static void main(String[] args) throws IOException, CsvException
  {
    System.out.println("hello world");
    Reader reader = new FileReader(System.getProperty("user.dir") +"/src/test/resources/numbers.csv");
    
	List<String[]> data =readCSV(reader);
	for(String [] lines:data)
	  {
	  for(int i=0;i<lines.length;i++)
	    {
	    System.out.print(lines[i]);
	    }
	    System.out.println();
	    }
	}
	
  private static List<String[]> readCSV(Reader reader) throws IOException, 
  CsvException {
		// TODO Auto-generated method stub
		CSVReader read = new CSVReader(reader);
		List<String[]> l = read.readAll();
		reader.close();
		read.close();
		return l;
	}
}

41) How to scroll up or down a page in Selenium by specific pixel?

        public  void ScrollByPixel()
	{
	JavascriptExecutor jse = (JavascriptExecutor) Driver;
	jse.executeScript("window.scrollTo(0, -document.body.scrollHeight)");
	}

42) How to upload files using Selenium Webdriver?

  1. By using the Send Keys Method
element.sendKeys("imagepath");

2. By Using the Robot Class: The robot class is used to generate native system input events.

StringSelection strSelection = new StringSelection("MediaPath");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(strSelection, null);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
		}

3) By Using AutoIt

Visit here to download and use.

43) How to perform swipe operations in Selenium.

Swipe operation can be performed using the Actions class. This class provides a method “moveByOffset” which moves the mouse from its current position to the offset provided by the user.

public void swipeFolders(WebElement elem) throws InterruptedException {
        Actions action = new Actions(Driver);
        action.clickAndHold(elem);
        action.moveByOffset(-193,0).release();
        action.build().perform();
       }

44) How to create a dynamic Xpath based on text in selenium?

Create a customized method.

        public static WebElement getLinkElement(String text) {
	String xpath = "//a[text()='"+text+"']";
	return driver.findElement(By.xpath(xpath));		
	}

45) How to refresh the browser in Selenium?

A browser can be refreshed in multiple ways. Some of them are mentioned below:

1)By SendKeys

driver.findElement(By.name("s")).sendKeys(Keys.F5);
          Or
driver.findElement(By.name("s")).sendKeys("\uE035") (Ascii Value)

2)By Get method

driver.get(driver.getCurrentUrl());

3)By using Javascript Executor

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("history.go(0)")

46) How to count the total number of images/links on a page?

To count the total number of links or images, capture and save the list of web elements and calculate the size of the list.

List<WebElement> imageList = driver.findElements(By.tagName("img"));
System.out.println("total images : " + imageList.size());
for(WebElement e : imageList) {
System.out.println(e.getAttribute("alt") + " ---> "+ e.getAttribute("src"));
}

47) How to capture screenshots in Selenium?

Use the TakesScreenshot interface to capture the screenshot in Selenium.

public static String getBase64Image() {
return ((TakesScreenshot)DriverManager.getDriver()).getScreenshotAs(OutputType.BASE64);
	}

48) How to capture and accept an Alert Text?

public static String captureAlertTextAndAccept(WebDriver driver) {
	Alert alt = driver.switchTo().alert();
        String alt_msg = alt.getText();
        alt.accept();
        return alt_msg;
	}

49) How do take Full Page screenshots using the Ashot utility?

public static String captureFullPageScreenShot(WebDriver driver) throws WebDriverException, IOException {
String screenshotPath = System.getProperty("user.dir") + "/ScreenShots" + captureDateTime() + ".png";
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
				.takeScreenshot(driver);
ImageIO.write(screenshot.getImage(), "png", new File(screenshotPath));
return screenshotPath;
	}

50) Write Xpath containing And or OR.

tagname[@title='titleName' and @class='className']
tagname[text()='value']

Discover more from AutomationQaHub

Subscribe now to keep reading and get access to the full archive.

Continue reading