如何在python中使用硒接受弹出窗口

时间:2020-09-22 04:42:20

标签: python selenium popup

到目前为止,我目前在python中已经很好地使用了硒,但是我不确定如何接受站点正在创建的弹出消息。 enter image description here

我已经尝试使用

alert_obj = driver.switch_to.alert
alert_obj.accept()

,但我只是从python输出中得到一个错误,提示未找到警报:

Traceback (most recent call last):
  File "C:\Users\KDJ\Documents\GameJoiner\Main.py", line 42, in <module>
    alert_obj = driver.switch_to.alert
  File "C:\Users\KDJ\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 55, in alert
    alert.text
  File "C:\Users\KDJ\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\common\alert.py", line 67, in text
    return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"]
  File "C:\Users\KDJ\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\KDJ\AppData\Local\Programs\Python\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoAlertPresentException: Message: no such alert

我正在使用Chrome网络驱动程序。 有人知道我应该怎么做才能使它工作吗?

谢谢!

chrome_options = webdriver.ChromeOptions()

userProfile = "C:\\Users\\KDJ\\Documents\\GameJoiner\\User Data\\Default";

chrome_options.add_argument('user-data-dir='+userProfile)

driver = webdriver.Chrome('C:\\Users\KDJ\Documents\GameJoiner\chromedriver.exe', options=chrome_options)

1 个答案:

答案 0 :(得分:1)

我将用Java编写它:

boolean b = false;

while(!b) {

  try {

    driver.switchto().alert();

    b = true;

  } catch(Exception e) {}

}

您可以在Python中使用Try Except和bool()函数。