总之,我需要一些严肃的“简化”示例,说明如何用 Python 编写代码,无论元素是否存在,这些代码都会执行某些操作。我是编程新手,我已经查看了一天的帖子,但我似乎无法弄清楚……
这就是我想要做的。
from selenium.common.exceptions import NoSuchElementException, staleElementReferenceException
elem = driver.find_element_by_partial_link_text('Create Activity')
print("Searching for Create Activity.")
if elem.is_displayed():
elem.click() # this will click the element if it is there
print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!")
else:
print ("NO LINK FOUND")
因此,假设存在一个 LINK 是 element_by_partial_link_text(‘Create Activity’)
我得到了正确的回应…正在搜索创建活动。找到链接创建活动!并点击它!
我的问题是没有匹配的链接 element_by_partial_link_text('Create Activity')
我在 else 语句中没有得到我期望的结果。 print ("NO LINK FOUND")
我得到…
回溯(最近调用最后):文件“”,第 1 行,在文件“C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py”,第 341 行, 在 find_element_by_partial_link_text 返回 self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) File “C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py”,第 745 行,在 find_element {‘using’: by, ‘value’: value})[‘value’] File “C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote \webdriver.py”,第236行,在execute self.error_handler.check_response(response) File “C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py” ,第 194 行,在 check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {“method”:“部分链接文本”,“选择器”:“创建活动”}
我如何在 Python
中获取 selenium 以将此异常或错误转为不停止我的脚本并仅处理 ELSE
语句。
谢谢,
原文由 th2112 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以捕获异常并采取相应措施:
另外,我可能会修改测试以确保该元素确实是“可点击的”: