Python 中的 Selenium 如果元素不存在,如何使用 If - else 代码

新手上路,请多包涵

总之,我需要一些严肃的“简化”示例,说明如何用 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 许可协议

阅读 693
2 个回答

您可以捕获异常并采取相应措施:

 try:
    elem = driver.find_element_by_partial_link_text('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!")
except NoSuchElementException:
    print("...")

另外,我可能会修改测试以确保该元素确实是“可点击的”:

 if elem.is_displayed() and elem.is_enabled():

原文由 ewcz 发布,翻译遵循 CC BY-SA 3.0 许可协议

find_element 返回元素或抛出 NoSuchElementException ,因此为了确定元素是否存在 if 条件的最佳方法,您应该尝试使用 find_elements 异常,因为它不是捕获异常—返回 WebElement 的列表或空列表,因此您只需检查其长度如下:-

 elems = driver.find_elements_by_partial_link_text('Create Activity')

if len(elems) > 0 and elems[0].is_displayed():
    elems[0].click()
    print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!")
else:
    print ("NO LINK FOUND")

原文由 Saurabh Gaur 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题