嘿,Brilliant Stack Overflow 社区,
我遇到了一个关于处理警报的有趣场景,例如弹出的用户身份验证框。
1:使用的网站(练习网站):https://the-internet.herokuapp.com/ https://the-internet.herokuapp.com/
2: When I clicked in to Basic Auth, there was a alert like pop up window show up (see below).
3:到目前为止我尝试过的。
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
chrome_path = '.\chromedriver.exe'
chrome_service = Service(chrome_path)
chrome = webdriver.Chrome(service=chrome_service)
chrome.maximize_window()
chrome.get('https://the-internet.herokuapp.com/')
basic_auth = WebDriverWait(chrome,timeout=30).until(expected_conditions.element_to_be_clickable((By.PARTIAL_LINK_TEXT,'Basic Auth')))
basic_auth.click()
3-1:将其视为警报(switch_to.alert)并使用发送键插入用户名和密码。但得到了 NoAlertPresentException。
chrome.switch_to.alert.send_keys('user\npass')
# get selenium.common.exceptions.NoAlertPresentException
3-2:将其视为活动元素并使用发送键。这次没有错误,但也没有任何内容发送到输入框。在我看来,这个弹出窗口不能成为一个元素。
chrome.switch_to.active_element.send_keys('user\npass')
# No error msg, but nothing show up in the pop up input field too.
3-3:将其视为一个新窗口,但在检查有多少个活动窗口(driver.window_handles)时,只有一个窗口。所以这个弹出窗口也不是一个窗口。
print(len(chrome.window_handles)) # return 1, so the pop up is not a window too
3-4:我偶然发现了这篇文章,但我不确定我是否理解解决方案是什么。Python Selenium 警报身份验证问题 https://stackoverflow.com/questions/42542603/python-selenium-alert-authentication-trouble
如果有人能帮助我了解如何浏览像这样的非网络元素,我将非常高兴。
太感谢了!
=======
问题更新
非常感谢@Tyzeron 和@Nic Laforge 的帮助!
我尝试了帖子中提到的两种方法,想知道我是否做得正确?
仅供参考:该网站本身是一个练习网站,因此每次您输入用户名和密码然后登录时,该网站都会生成一个新的基本身份验证弹出窗口。很难说我尝试的方法是否有效。
方法一:使用get方法时,将Basic Authentication放在URL中。
chrome_path = '.\chromedriver.exe'
chrome_service = Service(chrome_path)
chrome = webdriver.Chrome(service=chrome_service)
chrome.maximize_window()
chrome.get('https://username:[email protected] /cdn-cgi/l/email-protection/basic_auth')
方法2:使用Selenium Wire(我不确定我的代码是否正确)
from seleniumwire import webdriver as wire_driver
import base64
def request_interceptor(req):
# add Authentication Here.
# VXNlck5hbWU6UHNkMTIz is the base64 encoded str for "UserName:Psd123"
req.headers['Authorization'] = 'Basic VXNlck5hbWU6UHNkMTIz=='
print(req.headers)
chrome_path = '.\chromedriver.exe'
chrome_service = Service(chrome_path)
chrome = wire_driver.Chrome(service=chrome_service)
chrome.maximize_window()
chrome.request_interceptor = request_interceptor
chrome.get('https://the-internet.herokuapp.com/basic_auth')
使用 selenium-wire 的第二种方法也没有生成错误,但页面上没有可见的线索表明成功与否。
In addition, the printed result for req object in the function looks as follow:
现在,这两种方法都没有生成错误不可见的线索来表明代码成功。所以我想知道如何判断它是否有效?