Fault-Tolerant Selenium Text Scraper for Dynamic Pages
System DesignModel answerLast updated
Write a Python function that waits for two CSS-selected elements to become visible on a JS-rendered page and returns their text, with None for any that time out.
Background
Modern web pages often render their content asynchronously. A navigation bar might appear instantly, while a user profile panel loads after an API call completes. Automation code that reads elements immediately after page load will fail intermittently — not always, which makes the bugs hard to catch.
Your job is to write a function that handles this reality gracefully.
Task
Implement get_element_texts(driver, selector_1, selector_2) in Python.
The function accepts a live Selenium WebDriver instance and two CSS selector strings. It should locate the first matching element for each selector, wait until it is both present in the DOM and visible on screen, then return its text content. If an element does not become visible within 5 seconds, return None for that element instead of raising an exception.
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):
# your implementation here
pass
Requirements
- Use explicit waits. Do not use
time.sleep()anywhere in your solution. - The two elements must be handled independently. A timeout on one must not prevent the other from being attempted.
- Treat an element that exists in the DOM but is not visible the same as an element that is absent — both should produce
None. - When a selector matches more than one element, use the first match in document order.
Example
selector_1 = "#page-heading"
selector_2 = "#account-display-name"
The heading is present immediately. The account name appears after a 2-second AJAX call.
Expected return value: ["Welcome back!", "Ada Lovelace"]
Edge Cases to Handle
| Scenario | Expected return value for that slot |
|---|---|
| Element appears immediately | Its text string |
| Element appears via AJAX within 5 s | Its text string |
| Element is in the DOM but hidden | None |
| Element never appears within 5 s | None |
| Element is visible but has empty text | "" (not None) |
| Selector matches multiple elements | Text of the first match |
DOM re-renders while reading .text | Retry transparently, do not crash |
Be prepared to discuss how you would extend this to handle a list of N selectors, and how the timeout strategy should change in that case.
Hints
Hint 1
WebDriverWait polls a callable until it returns a truthy value or the deadline passes. Think about what your polling condition should return — and remember that an empty string is falsy in Python, which can cause a subtle bug if you return el.text directly.
Hint 2
Wrap each element lookup in its own try/except TimeoutException block. This keeps the two waits fully independent: a failure on selector_1 never skips selector_2.
Hint 3
Between the moment WebDriverWait decides an element is visible and the moment your code reads .text, the DOM could re-render, leaving you with a stale reference. Adding StaleElementReferenceException to the wait's ignored_exceptions list turns that race condition into a transparent retry.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is that you cannot trust the DOM to be stable or complete at any given moment. The right tool is WebDriverWait, which polls a condition on a short interval (0.5 s by default) and returns as soon as the condition is satisfied or the deadline passes. That eliminates busy-waiting with time.sleep() and lets the function respond the instant an element is ready rather than waiting out a fixed delay.
For each selector the function needs to:
- Locate the first matching element.
- Check that it is visible (not just present).
- Read its text.
- Return
Noneif any of the above doesn't succeed within 5 seconds.
Steps 1–3 are deliberately bundled into a single polling condition rather than performed in sequence. If they were separate steps, a DOM re-render between step 2 and step 3 would produce a StaleElementReferenceException that escapes to the caller. Inside the condition, staleness is just a signal to retry on the next poll.
The Empty-String Trap
WebDriverWait.until() treats any falsy return value from the condition as "not ready yet." An empty string is falsy, so if the condition returned element.text directly, a visible element with no text content would poll until timeout and ultimately resolve to None — wrong behavior. The fix is to wrap the result in a one-element tuple (element.text,), which is always truthy, then unpack it after the wait.
Per-Element Isolation
Each selector gets its own try/except TimeoutException. This means both lookups are always attempted; a missing first element does not short-circuit the second. The function always returns a list of exactly two values.
Visibility vs. Presence
find_element confirms the element exists in the DOM. is_displayed() confirms it is actually rendered and visible — it returns False for elements with display: none, visibility: hidden, or zero dimensions. The spec treats hidden elements the same as absent ones, so the condition returns False (keep polling) until is_displayed() is True.
Code
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import (
TimeoutException,
StaleElementReferenceException,
)
TIMEOUT_SECONDS = 5
def _visible_text_condition(locator):
"""
Returns a WebDriverWait-compatible condition.
Resolves to (text,) once the first matching element is visible.
Returns False to keep polling if the element is absent or hidden.
Stale element references are caught here so the wait retries them
instead of letting them propagate to the caller.
"""
def condition(driver):
try:
element = driver.find_element(*locator) # first match; NoSuchElement retried by default
if not element.is_displayed():
return False
return (element.text,) # wrap in tuple: empty string must not look like "not ready"
except StaleElementReferenceException:
return False # DOM changed mid-read; retry on next poll
return condition
def _get_text_or_none(driver, css_selector, timeout=TIMEOUT_SECONDS):
locator = (By.CSS_SELECTOR, css_selector)
wait = WebDriverWait(driver, timeout)
try:
(text,) = wait.until(_visible_text_condition(locator))
return text
except TimeoutException:
return None
def get_element_texts(driver, selector_1, selector_2):
"""
Return [text_1, text_2].
Each entry is the visible text of the matched element,
or None if it did not become visible within the timeout.
"""
return [
_get_text_or_none(driver, selector_1),
_get_text_or_none(driver, selector_2),
]
For the example, get_element_texts(driver, "#page-heading", "#account-display-name") returns ["Welcome back!", "Ada Lovelace"].
Complexity
- Time: O(T) wall-clock per element, where T = 5 s. Worst case is ~10 s total when both elements are absent, because the waits run sequentially.
- Space: O(1) beyond the two returned strings.
Common Mistakes
- Using
time.sleep()— it either waits too long or not long enough, and it burns time even when the element is already there. - Using
EC.presence_of_element_locatedinstead of a visibility check — this returns the element as soon as it hits the DOM, even if it's hidden, violating the spec. - Not isolating the two waits — a single
try/exceptblock around both lookups means selector_2 is skipped whenever selector_1 times out. - Returning
element.textdirectly from the condition — triggers the empty-string falsiness bug described above. - Caching a
WebElementreference across a potential re-render — always re-locate inside the polling loop.
Follow-Up: N Selectors
Extending to a list of selectors with return [_get_text_or_none(driver, s) for s in selectors] works correctly but has a worst-case runtime of N × 5 s. If a shared deadline is needed (e.g., "all elements within 10 s total"), compute deadline = time.monotonic() + budget and pass max(0, deadline - time.monotonic()) as each wait's timeout. A more advanced option is a single polling loop that checks all unresolved selectors on each tick and returns once every element is settled, reducing total round trips. Parallel execution via threads is possible but inadvisable — a single WebDriver session is not thread-safe.