Selenium Scripting & Execution Processes 3 — Questions and Answers
Question 1: Which Selenium command is used to retrieve the current URL of the browser?
- driver.getURL()
- driver.currentUrl()
- driver.getCurrentUrl() (Correct answer)
- driver.fetchUrl()
Correct answer: driver.getCurrentUrl()
driver.getCurrentUrl() returns the URL of the page currently loaded in the browser.
Question 2: What is the purpose of driver.manage().timeouts().implicitlyWait() in Selenium?
- Sets a maximum page load time
- Tells WebDriver to poll the DOM for a set duration when locating elements (Correct answer)
- Pauses script execution for a fixed time
- Sets the timeout for JavaScript execution
Correct answer: Tells WebDriver to poll the DOM for a set duration when locating elements
implicitlyWait() sets a global timeout that makes WebDriver poll for an element before throwing NoSuchElementException.
Question 3: In Selenium, how do you switch to a child window after clicking a link that opens a new tab?
- driver.switchTo().newWindow()
- driver.switchTo().window(windowHandle) (Correct answer)
- driver.focusWindow(handle)
- driver.changeWindow(handle)
Correct answer: driver.switchTo().window(windowHandle)
driver.switchTo().window(handle) switches the driver's context to the window with the specified handle.
Question 4: Which approach should be preferred over Thread.sleep() for synchronization in Selenium scripts?
- driver.pause()
- Explicit waits with WebDriverWait (Correct answer)
- driver.waitFor()
- System.sleep()
Correct answer: Explicit waits with WebDriverWait
Explicit waits using WebDriverWait with ExpectedConditions are more reliable and efficient than fixed Thread.sleep() pauses.
Question 5: How do you read a value from a text input field using Selenium WebDriver?
- element.getText()
- element.getValue()
- element.getAttribute("value") (Correct answer)
- element.getInput()
Correct answer: element.getAttribute("value")
getAttribute("value") retrieves the current value of a form input element, as getText() returns the visible text between tags.
Question 6: What happens if you call driver.findElement() and the element does not exist in the DOM?
- Returns null
- Returns an empty WebElement
- Throws NoSuchElementException (Correct answer)
- Throws ElementNotFoundException
Correct answer: Throws NoSuchElementException
findElement() throws NoSuchElementException immediately (or after implicit wait timeout) if no matching element is found.
Question 7: Which Selenium locator strategy is generally considered most robust and maintainable for long-term test scripts?
- XPath with absolute paths
- CSS selectors by tag name only
- By ID or custom data attributes (Correct answer)
- By element index position
Correct answer: By ID or custom data attributes
IDs and custom data-* attributes are stable, purpose-built for testing, and not affected by UI restructuring.
Which Selenium command is used to retrieve the current URL of the browser?