Selenium with Python has become one of the most sought-after skills in test automation roles today. From fintech startups to established MNCs like Grab, DBS Bank, and Shopee in Singapore, companies are hiring QA and SDET professionals proficient in Python Selenium automation. Whether you're preparing for your first job or targeting advanced Selenium Python interview roles, this guide compiles the Top Python Selenium Interview Questions and Answers, designed to help you tackle real-world scenarios, automation frameworks, and coding logic confidently.
Each question is accompanied by a theoretical explanation followed by a Python code snippet, ensuring you’re not just memorising answers but understanding the automation context behind them. These include python selenium interview questions for freshers, selenium python questions for experienced, and even tricky selenium with python questions often asked in senior roles.
Top Python Selenium Interview Questions
1. What is Selenium, and why is Python preferred with it?
Sample Answer: Selenium is an open-source automation testing tool for web applications across different browsers and platforms. Python is preferred with Selenium due to its simple syntax, large community, and powerful libraries. Python makes it easier to write clear and concise test scripts. It also integrates well with frameworks like PyTest and tools like Allure and Jenkins for reporting and CI/CD.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
2. How do you locate elements in Selenium using Python?
Selenium provides several methods to locate web elements: by ID, name, class, tag name, XPath, CSS selector, and link text. Among these, XPath and CSS selectors are the most flexible. Choosing the right locator strategy ensures test stability and maintainability.
driver.find_element(By.ID, "username")
driver.find_element(By.XPATH, "//input[@type='text']")
3. What is the role of WebDriver in Selenium?
The WebDriver API is the core interface to interact with browsers. Each browser (Chrome, Firefox, Safari, etc.) has a corresponding driver like ChromeDriver or GeckoDriver. WebDriver launches browsers, executes actions (click, type, scroll), and fetches responses. It mimics real user behavior at the DOM level.
driver = webdriver.Firefox()
driver.get("https://testsite.com")
4. How do you handle dropdowns using Selenium in Python?
To work with dropdowns, Selenium uses the Select
class from selenium.webdriver.support.ui
. You can select by index, visible text, or value.
from selenium.webdriver.support.ui import Select
dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text("India")
5. What are different types of waits in Selenium?
Waits help sync test execution with real-time browser actions. Selenium offers three types:
- Implicit Wait: Applies globally, waits for a fixed time for elements to appear.
- Explicit Wait: Waits for a specific condition like visibility or clickability.
- Fluent Wait: Advanced form of explicit wait with polling intervals and exception handling.
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "login")))
6. How do you handle alerts in Selenium?
Alerts are pop-up dialog boxes. Selenium can switch to an alert and perform actions like accept, dismiss, or retrieve text.
alert = driver.switch_to.alert
print(alert.text)
alert.accept()
7. What is the use of ActionChains in Selenium?
ActionChains are used to perform advanced interactions such as mouse hover, right-click, drag and drop, and double-click. These are useful when normal element methods aren’t enough for dynamic UI events.
from selenium.webdriver.common.action_chains import ActionChains
action = ActionChains(driver)
action.move_to_element(menu).click().perform()
8. How do you take a screenshot in Selenium with Python?
You can capture a screenshot of the browser window using the save_screenshot()
method. It’s helpful for debugging failed test cases or logging steps.
driver.save_screenshot("homepage.png")
9. How do you scroll down a webpage in Selenium?
Use JavaScript execution to scroll vertically or horizontally. This is especially useful for lazy-loaded content or infinite scroll pages.
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
10. How do you close the browser window in Selenium?
Selenium provides two methods:
driver.close()
: Closes the current browser tab.driver.quit()
: Closes all tabs and ends the WebDriver session.
driver.quit()
Read Also: Most-Asked Selenium Interview Questions and Answers
Intermediate Python Selenium Questions
11. How do you handle dropdowns using Selenium in Python?
In Selenium Python, handling dropdowns is streamlined with the `Select` class from `selenium.webdriver.support.ui`. Dropdowns built with the HTML `
12. How do you wait for an element to be visible or clickable in Python Selenium?
Waiting is essential in Selenium to avoid flaky tests. Python Selenium provides `WebDriverWait` with `expected_conditions` for explicit waits. Instead of using hard-coded sleeps, which slow down execution, it’s better to use waits that respond dynamically when the condition is true—like when an element becomes visible or clickable.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, "submit")))
element.click()
13. How can you perform mouse hover actions in Selenium with Python?
Mouse interactions like hover are managed using the `ActionChains` class. This is useful for triggering hidden dropdowns or tooltips. You first locate the element and then perform a hover action. Selenium simulates real user interaction with the browser, so the hover must be precise to avoid element misalignment issues.
from selenium.webdriver.common.action_chains import ActionChains
menu = driver.find_element(By.ID, "menu")
ActionChains(driver).move_to_element(menu).perform()
14. How do you take a screenshot using Selenium Python?
Capturing screenshots is a useful debugging technique. In Selenium Python, the `save_screenshot()` or `get_screenshot_as_file()` methods help you capture the current state of the browser. This is particularly useful when tests fail, allowing QA teams to analyse the UI at that moment.
driver.save_screenshot("homepage.png")
15. How do you verify the presence of a web element?
To check whether a web element exists, you can use `find_elements()` instead of `find_element()`. The former returns an empty list if no element is found—this helps you avoid exceptions and write cleaner logic to verify presence.
elements = driver.find_elements(By.ID, "logo")
if elements:
print("Element is present")
else:
print("Element not found")
16. How do you handle alerts and popups in Selenium with Python?
JavaScript alerts are handled using `switch_to.alert`. This allows you to accept, dismiss, or get the text from alerts. It’s crucial to use waits before accessing alerts, especially if they are triggered by asynchronous actions.
alert = driver.switch_to.alert
print(alert.text)
alert.accept()
17. How do you count the number of links on a webpage using Selenium Python?
To count links, locate all `` tags using `find_elements`. This is useful for accessibility and SEO-related test cases, where link counts and href validation are necessary.
links = driver.find_elements(By.TAG_NAME, "a")
print("Total links:", len(links))
18. What is the difference between find_element and find_elements in Selenium Python?
`find_element` returns a single web element and throws an exception if it’s not found. `find_elements` returns a list and doesn’t raise an exception—it just returns an empty list if no elements match. Always use `find_elements` when you expect zero or more elements, like validating lists, tables, or optional UI sections.
19. How do you handle iframes in Python Selenium?
To interact with elements inside an iframe, you must switch the driver context to the frame first. You can do this using name, ID, index, or WebElement. Always remember to switch back to the default content after the interaction is done.
driver.switch_to.frame("iframe_id")
# perform actions
driver.switch_to.default_content()
20. How do you scroll down a page using Selenium with Python?
Scrolling is handled using JavaScript execution. You can scroll to a specific position or until an element is in view. This helps when dealing with lazy-loaded content or fixed viewport sections.
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Scenario-Based Python Selenium Questions
21. How would you test a login page using Selenium Python?
Login pages are one of the most common test scenarios. You validate field presence, input behaviour, error messages, and successful redirects. Always use locators that are stable (like `name`, `id`, or data attributes). Additionally, you should assert the landing page post-login using title or URL checks.
# Locate elements
driver.find_element(By.ID, "username").send_keys("test_user")
driver.find_element(By.ID, "password").send_keys("test_pass")
driver.find_element(By.ID, "loginBtn").click()
# Assertion
assert "dashboard" in driver.current_url
22. How do you handle CAPTCHA on a page while automating with Selenium?
CAPTCHAs are intentionally designed to block bots. The best practice is to avoid automating flows where CAPTCHA is involved, or to disable them in test environments. If you must proceed, integrate third-party CAPTCHA solvers like 2Captcha, or handle the login manually before automation continues.
Note: No Selenium code shown here as CAPTCHA bypassing often requires external service APIs and violates site terms.
23. How do you test file uploads using Selenium with Python?
You can send the full file path directly to the input field of type “file”. This bypasses the OS-level file dialog and works for most modern browsers. Make sure your test file is accessible at runtime and avoid hard-coded paths.
upload = driver.find_element(By.ID, "uploadInput")
upload.send_keys("/path/to/testfile.pdf")
24. How do you automate a dynamic table and retrieve cell values in Selenium Python?
Dynamic tables change based on filters or pagination. Use XPath to target specific rows/columns, or loop through table rows and extract data using tag names. Always use conditions to validate headers before parsing values.
rows = driver.find_elements(By.XPATH, "//table[@id='orders']/tbody/tr")
for row in rows:
cols = row.find_elements(By.TAG_NAME, "td")
print(cols[0].text, cols[1].text)
25. How do you validate a toast message or flash alert after form submission?
Toast or flash messages often appear briefly and may not be immediately in the DOM. Use `WebDriverWait` to wait for visibility or presence of the element. Use class names or ARIA roles for stable selectors.
toast = WebDriverWait(driver, 5).until(
EC.visibility_of_element_located((By.CLASS_NAME, "toast-message"))
)
assert "Successfully saved" in toast.text
26. How would you test pagination functionality using Selenium Python?
Testing pagination involves clicking on “Next”, “Previous”, or page numbers, and validating that the displayed results change accordingly. You can assert the text range or unique element per page.
# Click Next
driver.find_element(By.LINK_TEXT, "Next").click()
assert "Page 2" in driver.page_source
27. How do you verify broken links using Selenium and Python?
Selenium alone can’t verify HTTP status codes, but you can extract all link URLs using Selenium and use Python’s `requests` module to validate their response codes.
import requests
links = driver.find_elements(By.TAG_NAME, "a")
for link in links:
url = link.get_attribute("href")
if url:
res = requests.head(url)
if res.status_code >= 400:
print("Broken link:", url)
28. How do you test for responsive design using Selenium Python?
Responsive testing involves setting different window sizes using `set_window_size()` and validating element visibility, layout changes, or class modifications across breakpoints.
# Mobile viewport
driver.set_window_size(375, 667)
assert driver.find_element(By.ID, "hamburger-menu").is_displayed()
29. How do you verify email confirmation or OTP workflows in automation?
This cannot be done via Selenium alone. Use temporary email APIs (like Mailinator) or integrate with Gmail/Outlook API to fetch email content. For OTPs, use DB hooks or stubs if the app supports it in test environments.
Note: Email verification logic typically relies on API or IMAP scripting in parallel with Selenium.
30. How would you test multi-window or tab handling in Selenium Python?
When a new tab opens, you need to switch Selenium’s control to the new window using `window_handles` and `switch_to.window()`. Always validate titles or unique elements before interacting.
main_tab = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Open Docs").click()
tabs = driver.window_handles
driver.switch_to.window(tabs[1]) # Switch to new tab
assert "Documentation" in driver.title
Framework and Automation Design
31. What are the key components of a Selenium test automation framework?
A well-designed Selenium framework includes:
– **Test Data Management**: Externalising test data using JSON, Excel, or YAML.
– **Object Repository**: Storing locators centrally using Page Object Model.
– **Logging and Reporting**: Using tools like `logging`, `Allure`, or `HTMLTestRunner`.
– **Assertions**: Using `unittest`, `pytest`, or `assert` statements.
– **Browser Driver Setup**: With cross-browser handling.
– **Test Runner**: Like `pytest`, `unittest`, or CI tools (Jenkins, GitHub Actions).
# Example: Logging config
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Test started")
32. What is the Page Object Model (POM) and why is it important?
POM separates test logic from UI element locators. Each page has a class, and all actions (like clicking buttons or fetching text) are methods inside that class. This promotes reusability, reduces code duplication, and improves maintainability.
# login_page.py
class LoginPage:
def __init__(self, driver):
self.driver = driver
self.username = driver.find_element(By.ID, "username")
def login(self, user, pwd):
self.username.send_keys(user)
self.driver.find_element(By.ID, "password").send_keys(pwd)
self.driver.find_element(By.ID, "loginBtn").click()
33. How do you implement test data-driven testing in Selenium Python?
Data-driven testing uses external data sources like Excel, CSV, JSON, or YAML files. With `pytest.mark.parametrize`, you can feed multiple data sets into the same test function, reducing redundancy and increasing coverage.
@pytest.mark.parametrize("user, pwd", [("admin", "admin123"), ("user", "user123")])
def test_login(user, pwd):
LoginPage(driver).login(user, pwd)
assert "dashboard" in driver.current_url
34. What are some best practices for designing a robust Selenium automation suite?
– Use POM to separate UI logic.
– Integrate waits (`WebDriverWait`) to prevent flakiness.
– Externalise config (URL, credentials, etc.) via `.env` or YAML.
– Use CI pipelines for automation.
– Capture screenshots on failure.
# Screenshot on failure
driver.save_screenshot("fail_screenshot.png")
35. How can you implement reusable functions in Selenium framework?
Wrap common actions (e.g. click, type, wait) inside utility/helper methods. This centralises error handling and logging, and keeps your test scripts clean and readable.
# helpers.py
def click_element(driver, locator):
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(locator)).click()
36. What are hooks in Pytest and how do they help?
Pytest hooks like `conftest.py` enable setup and teardown logic across test sessions. You can define fixtures for browser setup, login, database connection etc. to reduce redundancy and ensure consistent test environments.
# conftest.py
@pytest.fixture
def browser():
driver = webdriver.Chrome()
yield driver
driver.quit()
37. What is the role of `conftest.py` in a Selenium Pytest project?
`conftest.py` is a special file in Pytest where you declare fixtures and hooks. It is automatically discovered and applied across test files. For Selenium, it usually includes browser setup, login steps, and teardown routines.
# Reuse browser fixture
def test_title(browser):
browser.get("https://example.com")
assert "Example" in browser.title
38. How do you generate reports in Selenium Python projects?
You can generate test reports using:
– `pytest-html` for simple HTML reports
– `Allure` for rich, interactive reports
– Custom logging with `unittest` + `HTMLTestRunner`
# Run with HTML report
pytest --html=report.html
39. What is the use of `pytest.ini` in Selenium automation?
`pytest.ini` stores configurations like marker names, test paths, log levels, etc. It helps control the Pytest behaviour centrally, such as ignoring warnings, setting base URLs, or tagging tests.
[pytest]
markers =
smoke: Quick checks
regression: Full suite
40. How do you structure folders in a Selenium Python project?
A clean structure includes:
– `/tests`: Test scripts
– `/pages`: Page Object classes
– `/utils`: Helpers and config
– `/reports`: Screenshots & logs
– `conftest.py`, `pytest.ini`: Root-level configs
project/
├── tests/
├── pages/
├── utils/
├── reports/
├── conftest.py
├── pytest.ini
Tricky Python Selenium Questions
41. How can you handle dynamic web elements that change every time the page loads?
Dynamic elements usually have IDs or classes that change at runtime. Use stable attributes like `name`, `placeholder`, partial `XPath`, or `CSS` based on `contains()` or `starts-with()` functions. Avoid hardcoded values and use explicit waits to ensure timing consistency.
# Using XPath contains
element = driver.find_element(By.XPATH, "//input[contains(@id, 'user')]")
42. What if your script passes locally but fails on CI/CD server like Jenkins?
This is often caused by environment differences. Common issues include:
– Screen resolution mismatch
– Headless browser not behaving identically
– Missing WebDriver path or environment variables
– Test dependency not installed
– Timing issues not handled via waits
Use headless mode with correct options and set consistent environments.
# Headless Chrome
options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
43. How do you capture browser logs in Selenium using Python?
You can enable logging preferences in ChromeOptions to fetch logs related to network, console, or performance. This helps identify JS errors or network failures during UI automation.
options = webdriver.ChromeOptions()
options.set_capability("goog:loggingPrefs", )
driver = webdriver.Chrome(options=options)
logs = driver.get_log("browser")
44. How would you verify if a file is downloaded successfully using Selenium?
Selenium doesn’t track download progress. You must monitor the file system to check whether the expected file appears. Use Python’s `os` module to scan the download directory and verify.
# Check if file exists
import os
file_exists = os.path.exists("/downloads/report.csv")
assert file_exists
45. Can you explain the difference between find_element and find_elements in Selenium?
– `find_element` returns the **first** matching WebElement and throws `NoSuchElementException` if not found.
– `find_elements` returns a **list** of all matching elements and returns an **empty list** if none are found. Use `find_elements` when multiple matches are expected.
# Example
elements = driver.find_elements(By.CLASS_NAME, "btn")
print(len(elements))
46. How do you handle JavaScript alerts, confirms, and prompts?
Use Selenium’s `switch_to.alert` to work with JavaScript popups. You can accept, dismiss, or enter text into alerts depending on the type.
alert = driver.switch_to.alert
print(alert.text)
alert.accept() # or alert.dismiss(), alert.send_keys("value")
47. How do you automate a CAPTCHA-protected login page?
CAPTCHAs are meant to prevent automation. You can:
– Ask the dev team to disable CAPTCHA for automation environment
– Use third-party CAPTCHA solving services (not recommended for real projects)
– Skip CAPTCHA logic entirely for test accounts
No ideal automation exists for CAPTCHA due to legal and ethical limitations.
48. How do you retry a failed Selenium test automatically in Python?
Use `pytest-rerunfailures` plugin to retry failed tests. This helps tackle flaky tests caused by UI timing or network hiccups.
# Retry test 2 times
pytest --reruns 2 test_sample.py
49. How do you validate text presence on a webpage?
Use `get_attribute`, `text`, or verify via XPath contains. Make sure you wait for the element before validation.
assert "Welcome" in driver.find_element(By.TAG_NAME, "body").text
50. How do you handle stale element reference exceptions?
This occurs when the DOM changes after locating an element. Solution:
– Re-locate the element before interacting again
– Use explicit waits to wait until element is reattached
# Retry locating
try:
driver.find_element(By.ID, "submit").click()
except StaleElementReferenceException:
time.sleep(1)
driver.find_element(By.ID, "submit").click()
Frequently Asked Questions
đź”˝ What is Selenium in Python used for?
đź”˝ How do I install Selenium for Python?
pip install selenium
. Then download the required WebDriver like ChromeDriver or GeckoDriver.đź”˝ Can Selenium run without opening a browser window?
đź”˝ What are common exceptions in Selenium Python?
NoSuchElementException
, TimeoutException
, StaleElementReferenceException
, and ElementNotInteractableException
.đź”˝ Is Selenium Python enough to get a QA job?
đź”˝ Can Selenium handle multiple browser tabs?
driver.window_handles
and driver.switch_to.window()
to switch between tabs.