我正在编写一个 Python (3.6.6) 脚本,它使用 Selenium (3.141.0) 在 Chrome(ChromeDriver 版本 77.0.3865.40)中打开一个 URL,导航一系列菜单,在弹出窗口中输入登录详细信息并登录。这是我的脚本:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
url = 'https://some.url.com/'
driver = webdriver.Chrome()
action = ActionChains(driver)
driver.get(url)
button_1 = driver.find_element_by_xpath("//*[contains(text(), 'button_1_text')]")
button_1.click()
button_2 = driver.find_element_by_id('button_2_text')
button_2 .click()
link = driver.find_element_by_link_text('link_text')
action.move_to_element(link).perform()
link.click()
alert_obj = driver.switch_to.alert
如果我手动执行此导航,我会收到要求输入用户名和密码的提示,并带有两个用于登录或取消的按钮。当 Selenium 执行此操作时,我看到提示闪烁,但随后很快消失,因此出现错误:
selenium.common.exceptions.NoAlertPresentException: Message: no such alert
如果我手动刷新仍然打开的浏览器,我可以让警报出现,但如果我编写刷新脚本,提示再次消失。我尝试过等待警报出现,如 Check if any alert exists using selenium with python 中所述。 ,但等待只是超时。
如果我检查警报消失后保持打开状态的页面的源代码,我会看到:
<!-- template name: form.autopost.template.html -->
<html>
<head>
<title>Submit Form</title>
</head>
<body onload="javascript:document.forms[0].submit()">
<noscript>
<p>
<strong>Note:</strong> Since your browser does not support JavaScript, you must press the Resume button once to proceed.
</p>
</noscript>
<form method="post" action="another_url.saml2">
<input type="hidden" name="SAMLRequest" value="really_long_token"/>
<input type="hidden" name="RelayState" value="token"/>
<noscript><input type="submit" value="Resume"/></noscript>
</form>
</body>
</html>
所以我尝试使用以下命令显式启用 JavaScript:
options = webdriver.ChromeOptions()
options.add_argument("--enable-javascript")
driver = webdriver.Chrome(chrome_options=options)
这似乎类似于 Selenium test - Firefox alert disappearing immediately ,但看起来我无法使用 Chrome 重新创建解决方案。我尝试了以下方法:
options = webdriver.ChromeOptions()
options.add_argument("--disable-popup-blocking")
driver = webdriver.Chrome(chrome_options=options)
但这也没什么区别。还有其他方法可以防止 Selenium/Chrome 自动关闭警报吗?
这是弹出窗口的屏幕截图:
我尝试将以下内容添加到我的脚本末尾:
current_url = driver.current_url
parts = current_url.split('//')
login_url = parts[0] + '//{}:{}@'.format(username, password) + parts[1]
driver.get(login_url)
但这没有帮助。登录 URL 如下所示:
https://username:password@some_site/1S14/idp/G6tue/resume/idp/prp.ping?pfidpadapterid=idp.CG2LlmzHFUrah4EmDQ7jO_XTLGP&rememberChoice=true
最佳答案
我为我的公司做了一个类似的项目,你需要做的是使用 UI 自动化(Lib:pyautogui)浏览到那个 URL,然后输入用户名和密码。之后,您可以自由地使用 Selenium 做任何事情。
您的代码不会超出“driver.get(url)”,它将永远停留在那里。
关于python - 在脚本可以使用 Selenium + Python + Chrome 切换到它之前警报消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397735/