Robust Selenium Code to Extract Text from Two Elements
GleanSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to write robust browser automation code using Selenium, focusing on handling dynamic content, timing issues, and basic error handling.
Problem Statement
You are tasked with writing a Python function get_element_texts(driver, selector_1, selector_2) that retrieves the text content from two specific web elements on a page. The page is dynamically rendered using JavaScript, meaning elements may not be present in the DOM immediately upon page load.
Your implementation must meet the following criteria:
- Robustness: You must use explicit waits to ensure elements are present and visible before attempting to interact with them. Do not use
time.sleep(). - Resilience: If one element is found but the second fails to load within a 5-second timeout, the function should return
Nonefor the missing element and the text for the found element rather than crashing. - Clarity: Use clear locator strategies (e.g.,
By.CSS_SELECTORorBy.ID).
Function Signature
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def get_element_texts(driver, selector_1, selector_2):
# Implementation goes here
pass
Example
- Input:
selector_1= "#header-title",selector_2= "#user-profile-name" - Scenario: The header loads instantly, but the profile name takes 2 seconds to appear via AJAX.
- Expected Output:
["Welcome!", "John Doe"]
Edge Cases to Consider
- An element exists in the DOM but is hidden (not visible).
- An element never appears within the timeout period.
- The page contains multiple elements matching the same selector (return the first match).
Hints
Hint 1
Utilize `WebDriverWait` combined with `expected_conditions.visibility_of_element_located` to handle the asynchronous nature of the page.
Hint 2
Wrap your logic for each element in a `try-except` block to catch `TimeoutException`, allowing the second element to be attempted even if the first fails.
Hint 3
Ensure you are passing the `driver` instance and a defined timeout duration to the `WebDriverWait` constructor.
Follow-up questions
- How would you refactor this code if you needed to retrieve text from a list of 20 elements dynamically?
- What strategies would you use to handle 'stale element reference' exceptions if the DOM updates while your script is running?
- In a real-world testing suite, how would you design a custom Expected Condition to verify that a specific text pattern exists within an element?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.