如何在python中使用硒检查弹出警报

时间:2018-09-28 13:21:24

标签: python selenium selenium-webdriver

如果要删除的网页中有弹出消息,我要继续下一次迭代。那就是如果有任何弹出消息,我要接受该消息并转到下一项,即转到循环的开头。

为此,我使用以下代码段:

from tkinter import *
from tkinter import messagebox as msg
from tkinter import filedialog as fd
from tkinter import ttk
from tkinter import StringVar as sv
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException


for(i in range(0,5)):
      try:
          click_alert=driver.switch_to_alert()
          click_alert.accept()

          continue
      except TimeoutException:
           print('wrong value in'+i+'th row . Please check the value ') 

出现以下错误:

Tkinter回调中的异常

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:/Users/chowdhuryr/Desktop/ATT RESEARCH BOT/GUI.py", line 64, in printMessage
    self.Scrapper(str1,str2)
  File "C:/Users/chowdhuryr/Desktop/ATT RESEARCH BOT/GUI.py", line 163, in Scrapper
    click_alert=driver.switchTo().alert()

现在,我非常确定错误出在click_alert=driver.switch_to_alert()上,因为我已经使用一些完整性检查对其进行了检查。

2 个答案:

答案 0 :(得分:2)

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("url")
browser.find_the_element_by_id("add_button").click()

try:
    WebDriverWait(browser, 3).until(EC.alert_is_present(),
                                   'Timed out waiting for PA creation ' +
                                   'confirmation popup to appear.')

    alert = browser.switch_to.alert
    alert.accept()
    print("alert accepted")
except TimeoutException:
    print("no alert")

答案 1 :(得分:-3)

通常,我们不在for后面加上括号。并且,当您打算切换时,警报似乎还不存在。 for循环可能只是一个繁忙的等待,使CPU处于循环状态,因此,当警报窗口不存在时,您可以添加一段时间的睡眠,而不仅仅是保持CPU不必要的繁忙。 该代码段可以按以下方式更正:

npm start -- --reset-cache