ven*_*kat 7 python selenium alert webdriver selenium-webdriver
我想从警告框中读取文本.
如果在警告框中找到此文本,我必须关闭警报框:
要从“ 警报”框中读取文本,请验证并关闭警报,您必须先切换到“ 警报”,然后执行以下提到的步骤:
alert = chrome.switch_to_alert()
alert_text = alert.text
# validate the alert text
alert.accept()
Run Code Online (Sandbox Code Playgroud)
但是,现在似乎switch_to_alert()
已弃用。因此,根据当前的实现,您需要使用:
alert = driver.switch_to.alert()
alert_text = alert.text
# validate the alert text
alert.accept()
Run Code Online (Sandbox Code Playgroud)根据最佳实践,在切换到Alert之前,应始终为Alert_is_present()引入WebDriverWait,如下所示:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
alert = WebDriverWait(driver, 5).until(EC.alert_is_present)
alert_text = alert.text
# validate the alert text
alert.accept()
Run Code Online (Sandbox Code Playgroud)您可以在“ 为什么切换通过硒警报不稳定”中找到相关讨论。
我的框架中也有类似的情况,这就是我解决的方法。
if (_driver.FindElement(By.XPath("//*[text()[contains(.,'No Sales Found')]")).Enabled)
{
//Do Something
}
Run Code Online (Sandbox Code Playgroud)
将其放在可能引发错误的功能之后。另外,此示例使用 C# 和 _driver 作为驱动程序,这可能与您使用的不同。