要从警告框(Alert Box)中读取文本内容,验证并关闭警告(Alert),您需要先切换到警告(Alert),然后按照以下步骤进行:
alert = chrome.switch_to_alert()
alert_text = alert.text
# validate the alert text
alert.accept()
然而,现在似乎switch_to_alert()
已被弃用。因此,根据当前实现,您需要使用:
switch_to.alert()
as follows:
alert = driver.switch_to.alert()
alert_text = alert.text
# validate the alert text
alert.accept()
As per best practices you should always induce WebDriverWait for the alert_is_present() before switching to an Alert as follows:
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()
首先,您应该切换到警告窗口:
alert = driver.switch_to_alert()
通过使用alert.text
获取警告窗口上的文本。并检查您的文本是否正确。
然后执行以下操作(关闭警告窗口):
alert.accept()
我在我的框架中也遇到了类似的情况,这是我的解决方法。
if (_driver.FindElement(By.XPath("//*[text()[contains(.,'No Sales Found')]")).Enabled)
{
//Do Something
}
我不懂Python,但在Java中你可以这样做:
Alert alert = driver.switchTo().alert();
String msg=alert.getText();
if(msg.equals("Message you compare"))
{
alert.accept();
}