How to Handle HTTP Authentication in Selenium Tests
To handle
HTTP authentication in Selenium, you can embed the username and password directly in the URL like http://username:password@site.com. Alternatively, use browser-specific options or extensions to manage authentication dialogs automatically.Why This Happens
HTTP authentication prompts a browser popup asking for username and password before loading the page. Selenium cannot interact with this popup directly because it is a browser-level dialog, not part of the webpage DOM.
python
from selenium import webdriver browser = webdriver.Chrome() browser.get('http://example.com') # Site requires HTTP auth # Selenium cannot enter credentials here, test will fail or hang
Output
selenium.common.exceptions.UnexpectedAlertPresentException: unexpected alert open: Authentication required
The Fix
Embed the username and password in the URL to bypass the popup. Format the URL as http://username:password@site.com. This lets Selenium load the page with credentials automatically.
python
from selenium import webdriver username = 'user' password = 'pass' url = f'http://{username}:{password}@example.com' browser = webdriver.Chrome() browser.get(url) # Auth handled by URL embedding
Output
Page loads successfully without authentication popup
Prevention
To avoid authentication issues in Selenium tests:
- Use URL embedding for HTTP auth when possible.
- Use browser profiles or extensions that auto-fill auth dialogs.
- Prefer testing environments without HTTP auth or use API mocks.
- Keep credentials secure and avoid hardcoding in tests.
Related Errors
Other common errors include:
- UnexpectedAlertPresentException: Happens when an alert or auth popup blocks Selenium.
- NoSuchElementException: Trying to find elements inside auth popup which is not in DOM.
- TimeoutException: Waiting for page load fails due to auth blocking.
Fixes involve handling auth before page load or using browser options.
Key Takeaways
Embed credentials in the URL to bypass HTTP authentication popups in Selenium.
Selenium cannot interact with browser-level auth dialogs directly.
Use browser profiles or extensions to automate authentication if URL embedding is not possible.
Avoid hardcoding sensitive credentials in test scripts.
Test environments without HTTP auth simplify Selenium automation.