Selenium Advanced
1. What is the difference between XPath and CSS Selector in Selenium?
- XPath allows navigating through elements using hierarchical relationships, supporting both absolute (/) and relative (//) paths.
- CSS Selector is faster than XPath and works well with dynamic elements, but it doesn’t support direct traversal of parent nodes.
- Key Difference: XPath is more powerful but slower, while CSS is faster but has limited traversing abilities.
2. What is the Actions class in Selenium, and how is it used?
The Actions class in Selenium is used to perform advanced user interactions, such as:
- Mouse hover (moveToElement)
- Right-click (contextClick)
- Drag and drop (dragAndDrop)
- Double-click (doubleClick)
3. What is JavaScriptExecutor in Selenium?
JavaScriptExecutor is an interface in Selenium used to run JavaScript code within the browser.
Example:
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", element);
It is useful for clicking elements, scrolling pages, and handling disabled elements.
4. How do you handle a StaleElementReferenceException in Selenium?
A StaleElementReferenceException occurs when the referenced element is no longer in the DOM. Solutions:
- Re-locate the element before interacting with it.
- Use explicit waits:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(locator)));
5. How do you handle dynamic elements in Selenium?
Dynamic elements change frequently, so we use:
- Dynamic XPath:
//button[contains(text(), 'Check Availability')]
- Wait mechanisms (Explicit/Fluent Waits):
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button")));
6. What is an Object Repository in Selenium, and how do you use a .properties file?
An Object Repository stores UI elements separately, making tests more maintainable.
Using a .properties file:
- Store locators:
login.username = //input[@id='username']
- Read from the file:
Properties prop = new Properties(); FileInputStream file = new FileInputStream("config.properties"); prop.load(file); driver.findElement(By.xpath(prop.getProperty("login.username"))).sendKeys("testuser");
7. What is Page Factory in Selenium?
Page Factory is a design pattern that enhances Page Object Model (POM) by initializing elements using @FindBy annotation.
public class LoginPage { @FindBy(id = "username") WebElement username; @FindBy(id = "password") WebElement password; public LoginPage(WebDriver driver) { PageFactory.initElements(driver, this); } }
8. What are relative locators in Selenium 4?
Relative locators help find elements based on their position relative to other elements.
WebElement belowElement = driver.findElement(with(By.tagName("input")).below(referenceElement));
9. How do you handle an "Element Click Intercepted" exception?
This occurs when another element overlays the target element.
Solutions:
- Scroll into view:
js.executeScript("arguments[0].scrollIntoView(true);", element);
- Use Actions class:
Actions actions = new Actions(driver); actions.moveToElement(element).click().perform();
10. How do you take a screenshot of failed test cases in TestNG?
Use the ITestListener interface to capture screenshots in onTestFailure:
public void onTestFailure(ITestResult result) { File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("screenshot.png")); }
11. What are Listeners in Selenium?
Listeners in TestNG help track test execution status.
@Listeners(MyListener.class) public class TestClass { }
12. How do you handle multiple windows in Selenium?
String mainWindow = driver.getWindowHandle(); for (String window : driver.getWindowHandles()) { driver.switchTo().window(window); }
13. How do you switch between frames in Selenium?
driver.switchTo().frame(0); // By index driver.switchTo().frame("frameName"); // By name
To switch back:
driver.switchTo().defaultContent();
14. What are different ways to click an element in Selenium?
- Regular click: element.click();
- JavaScript click: js.executeScript("arguments[0].click();", element);
- Actions class click: actions.click(element).perform();
15. How do you send arrow key inputs in Selenium?
element.sendKeys(Keys.ARROW_DOWN); element.sendKeys(Keys.ARROW_UP);
16. What is the difference between Selenium 3 and Selenium 4?
- Selenium 4 introduced W3C WebDriver protocol, replacing JSON Wire Protocol.
- Relative locators
- Better window and tab handling
- Enhanced Grid architecture
17. How do you handle elements that sometimes pass and sometimes fail during automation?
- Use Explicit Waits: Selenium’s WebDriverWait to wait for elements dynamically.
- Implement Retry Mechanism: Re-run failed steps with a retry analyzer.
- Check Element State: Ensure the element is present, visible, and enabled before interacting.
- Use JavaScript Executor: When standard Selenium actions fail due to UI changes.
18. How do you handle dynamic elements in Selenium?
- Use dynamic XPath (contains(), starts-with(), following-sibling).
- Implement Explicit Waits to wait for elements dynamically.
- Use JavaScript Executor to interact with hidden elements.
- Use CSS Selectors for better element identification.
19. How do you handle browser compatibility testing in automation?
- Use Selenium Grid: Allows execution on multiple browsers in parallel.
- Leverage Cloud Platforms: Use BrowserStack, Sauce Labs for cross-browser testing.
- Run Tests on Different Browsers: Configure test execution using TestNG parameters or WebDriver capabilities (ChromeOptions, FirefoxOptions).
- Use Responsive Design Testing: Automate viewport resizing to check UI responsiveness.
- Ensure CSS and JavaScript Compatibility: Use browser developer tools and automation to verify UI consistency.