About Focusing an Element with Selenium
The following method of a Django Test Case with Selenium, scrolls to the middle of a viewport with an element by CSS selector, waits for the smooth animation to end if it is set, then focuses the element and returns it as a Selenium element:
def focus_element(self, css_selector):
self.browser.execute_script(
f"""
window.scrollComplete = false;
let element = document.querySelector('{css_selector}');
window.addEventListener('scrollend', function handleScrollEnd() {{
element.setAttribute('tabindex', '-1');
element.focus();
window.scrollComplete = true;
window.removeEventListener('scrollend', handleScrollEnd);
}}, {{ once: true }});
element.scrollIntoView({{ block: 'center', behavior: 'smooth' }});
// Fallback: if no scroll needed, complete immediately
setTimeout(() => {{
if (!window.scrollComplete) {{
element.setAttribute('tabindex', '-1');
element.focus();
window.scrollComplete = true;
}}
}}, 100);
"""
)
WebDriverWait(self.browser, 10).until(
lambda driver: driver.execute_script(
"return window.scrollComplete === true"
)
)
element = self.browser.find_element(By.CSS_SELECTOR, css_selector)
return element
Tips and Tricks Programming Testing Django 5.2 Django 4.2 Django 3.2 JavaScript Selenium
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.