python-3.x - 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 浏览器添加扩展名,就可以找到我在此处添加的示例。
解决方案
问题是这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
推荐阅读
- python - 如何使此代码在 Tkinter 中用于多项选择测验?
- html - 当父 div 包含特定单词时从 HTML 中提取值(多嵌套 div)
- linux - Bash 脚本:我的减法问题
- syntax - 是精度问题还是只是语法输入错误?
- java - 如何使用 RXJava 顺序链接 Vertx CompositeFuture?
- javascript - 如何使用 Knex.js 查询相似但不是自我?
- powershell - test-wsman 工作,但 enter-pssession 失败
- rest - WooCommerce Rest API - 使用 UTC 格式的 after 和 before 参数获取订单,返回本地时区的订单
- typescript - 将 Fetch Wrapper 转换为 Typescript
- linux - 在 shell 脚本中没有 List 的 for 循环