我想使用 Python3-Selenium 访问网站。但是,为了访问我的目标网站,我必须通过身份验证页面。
比如我要访问的URL目标网站是https://target_website.com 。而认证页面的URL为https://example.example.com/ab/cd/ef
这是页面示例:
正如您从上图中看到的,我必须:
- 填写用户名
- 填写密码
- 点击登录
尝试了以下代码,但没有成功。
browser = webdriver.Chrome('path_to_exe')
wait = WebDriverWait(browser, 600)
browser.get('https://target_website.com')
wait.until(EC.alert_is_present())
browser.get('https://<username>:<password>@example.example.com/ab/cd/ef')
尝试了下面的代码,还是不行。
browser = webdriver.Chrome('path_to_exe')
wait = WebDriverWait(browser, 600)
browser.get('https://target_website.com')
wait.until(EC.alert_is_present())
browser.get('https://<username>:<password>@example.example.com')
最后,我尝试了以下代码,但还是不行。
browser = webdriver.Chrome('path_to_exe')
wait = WebDriverWait(browser, 600)
browser.get('https://target_website.com')
wait.until(EC.alert_is_present())
alert = browser.switch_to_alert()
alert.authenticate('<username>', '<password>')
alert.accept()
最佳答案
尝试使用以下内容:
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox('path_to_exe')
wait = WebDriverWait(browser, 10)
browser.get('https://target_website.com')
alert = wait.until(EC.alert_is_present())
alert.send_keys('username' + Keys.TAB + 'password')
alert.accept()
请注意,此方法仅适用于 Firefox
关于Python3 Selenium在弹出对话框中填写用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819749/