简体   繁体   English

如何使用Python + Selenium从警告框中读取文本

[英]How to read the text from the alert box using Python + Selenium

I want to read the text from the alert box. 我想从警告框中读取文本。

If this text is found in the alert box I have to close the alert box: 如果在警告框中找到此文本,我必须关闭警报框:

警报框

To read the text from the Alert Box , validate and close the Alert you have to switch to the Alert first and follow the below mentioned steps: 要从警报框中读取文本,请验证并关闭警报,您必须先切换到警报,然后按照以下步骤操作:

alert = chrome.switch_to_alert()
alert_text = alert.text
# validate the alert text
alert.accept()

However, now it seems switch_to_alert() is deprecated . 但是,现在似乎不推荐使用 switch_to_alert() So as per the current implementation you need to use: 因此,根据您当前的实现,您需要使用:

  • switch_to.alert() as follows: switch_to.alert()如下:

     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: 根据最佳实践,您应始终在切换到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() 

You can find a relevant discussion in Why switching to alert through selenium is not stable? 您可以在为什么通过硒切换到警报不稳定的情况下找到相关的讨论

First of all, you should switch to the alert window: 首先,您应该切换到警报窗口:

alert = driver.switch_to_alert()

Then get the text on the alert window by using alert.text . 然后使用alert.text在警报窗口中获取文本。 And check your text for correctness. 并检查您的文本是否正确。

Then do such action (close the alert window): 然后执行此操作(关闭警报窗口):

alert.accept()

I have similar situations as this in my framework as well, and this is how I solved it. 在我的框架中我也有类似的情况,这就是我解决它的方式。

if (_driver.FindElement(By.XPath("//*[text()[contains(.,'No Sales Found')]")).Enabled)
{
     //Do Something
}

Put this after functionality that may bring the error up. 将此功能置于可能导致错误的功能之后。 Also, this example is using C# and _driver as the driver, which may be different from what you are using. 此外,此示例使用C#和_driver作为驱动程序,这可能与您使用的不同。

I dont know python but in java you can like this: 我不懂python,但在java中你可以这样:

Alert alert = driver.switchTo().alert();
String msg=alert.getText();
if(msg.equals("Message you compare"))
{
alert.accept();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM