【发布时间】:2019-07-06 10:09:53
【问题描述】:
目前正在编写一个使用 Selenium 填写在线表格的 Python 程序。填写并提交表单后,有 3 种可能的重定向。
我正在尝试编写一个函数来确定我被重定向到哪个页面。
我使用 3 个 try-except 块编写了一个函数,但我无法捕捉到 NoSuchElementException。
def match():
try:
match = driver.find_element_by_id("hi")
return 'condition 1'
except NoSuchElementException:
pass
try:
match = driver.find_element_by_id("hey")
return 'condition 2'
except NoSuchElementException:
pass
try:
match = driver.find_element_by_id("hello")
return 'condition 3'
except NoSuchElementException:
pass
return 'none'
我收到以下异常
引发异常类(消息、屏幕、堆栈跟踪) selenium.common.exceptions.NoSuchElementException:消息:无法找到元素:[id="hi"]
旁注:有人知道在 Python 中进行模式匹配的更优雅的方法吗?
【问题讨论】:
-
将以下行放在顶部:
from selenium.common.exceptions import NoSuchElementException
标签: python selenium pattern-matching conditional-statements try-except