首页 > 解决方案 > Selenium 无法在 python 中处理弹出窗口或警报

问题描述

我想在附加图像中获取弹出窗口的文本。现在我在 python 中使用 selenium 来获取这些文本值。以下是我的代码-

time.sleep(LOADING_TIME)
alert = driver.switch_to.alert
print(alert.text())

但是,当我这样做时,我收到以下错误 -

selenium.common.exceptions.NoAlertPresentException: Message: no such alert
  (Session info: chrome=69.0.3497.81)
  (Driver info: chromedriver=2.41.578706 (5f725d1b4f0a4acbf5259df887244095596231db),platform=Mac OS X 10.13.6 x86_64)

谁能告诉我我做错了什么?请注意:我正在使用 chrome 驱动程序来初始化 selenium 驱动程序,只要您想向 chrome 浏览器添加扩展名,就可以找到我在此处添加的示例。 在此处输入图像描述

标签: python-3.xseleniumpopupwindow

解决方案


问题是这driver.switch_to.alert是一个函数。

像这样改变它:

driver = webdriver.Chrome()
driver.get(your_url)

alert = driver.switch_to_alert()
alert.accept()

# Eventually do anything else.

driver.close()

[编辑]

由于 selenium 似乎无法识别对话框,您可以使用pywinauto 模块:获取对话框并与之交互。

from pywinauto import Application


driver_handle = driver.current_window_handle  # get driver window handle
app = Application().connect(handle = driver_handle)  # initialize app

dialog = pywinauto.app.top_window_()  # select the dialog

dlg.control.Addextension.Click()  # click on "Add extension" button

推荐阅读