我正在使用 Python Selenium 从列表中打开一个 URL 并找到某个元素。像这样...
driver.get('http://www.example.com.com/')
inputElement = driver.find_element_by_id("my-field")
如果该元素存在则一切正常,但如果找不到该元素则脚本会因错误而崩溃...
Unable to locate element:
这是正确的行为吗?有没有办法解决这个问题而不是崩溃?
请您参考如下方法:
这是正确的行为。
您可以捕获异常,就像捕获任何异常一样:
from selenium.common.exceptions import NoSuchElementException
...
try:
driver.get('http://www.example.com.com/')
inputElement = driver.find_element_by_id("my-field")
except NoSuchElementException:
print("couldn't find the element")
