python - 使用 Python 和 Selenium 处理警报

标签 python selenium selenium-webdriver alert

在此警报中,我尝试使用 Selenium 的 send_keys 元素方法编写登录凭据: Login Alert

我在新窗口中单击按钮后收到此警报,但无法检查此窗口上的元素。

这是我的代码

import time
import pynput
from selenium import webdriver

driver=webdriver.Chrome("C:/Users/dhias/OneDrive/Bureau/stgg/chromedriver.exe")
driver.get("http://10.15.44.177/control/userimage.html")
time.sleep(3)
window_before = driver.window_handles[0]
driver.maximize_window()
btn=driver.find_element_by_name("TheFormButton3")
btn.click()
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
obj = driver.switch_to.alert
time.sleep(2)
obj.send_keys('Admin')
time.sleep(2)

我收到此错误,告诉我没有警报

最佳答案

我无法访问该页面,因此无法尝试我的代码,但首先我通过添加 WebdriverWait 和新的 By. 函数对其进行了优化:

from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = wd.Chrome("C:/Users/dhias/OneDrive/Bureau/stgg/chromedriver.exe")
wait = WebDriverWait(driver, 15)

driver.get("http://10.15.44.177/control/userimage.html")
driver.maximize_window()
window_before = driver.window_handles[0]
wait.until(EC.element_to_be_clickable((By.NAME, "TheFormButton3"))).click()
driver.switch_to.window(driver.window_handles[1])

alert = driver.switch_to.alert
alert.send_keys('Admin\npassword\n') # \n works as an ENTER key

您可以尝试此代码来查看警报是否确实存在或者是网页的一个元素:

from selenium.common.exceptions import NoSuchElementException

def is_alert_present(self):
    try:
        self.driver.switch_to_alert().send_keys('Admin\npassword\n') # \n works as an ENTER key
        print('Sucess')
    except NoSuchElementException:
        print('No Alert Present')

另请参阅AlertsSelenium Documentation

也可以尝试:

parent_h = browser.current_window_handle
# click on the link that opens a new window
handles = browser.window_handles # before the pop-up window closes
handles.remove(parent_h)
browser.switch_to_window(handles.pop())
# do stuff in the popup
# popup window closes
browser.switch_to_window(parent_h)
# and you're back

关于python - 使用 Python 和 Selenium 处理警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71537664/

相关文章:

python - Selenium + Python 期望特定的已找到元素

java - 为什么 Firefox WebDriver 不会从以前的浏览器 session 中加载 Cookie?

firefox - 无法调用 FirefoxDriver 构造函数

python - 与不可见元素交互并访问第二个匹配元素

Python Selenium Webdriver `Failed to start browser: Permission Denied`

python - 我如何查看域是否使用DNSSEC

python - 使用 python-docx 迭代数据帧中的值以打印到 Word

python - 如何在定义全局方法时从继承类中动态选择子类

python - Pyspark 将列类型从日期更改为字符串

java - Allure Cucumber JVM 适配器 - 报告显示没有功能没有故事