首页 > 解决方案 > 当在硒中找不到项目时如何引发错误并继续使用不同的功能

问题描述

我正在尝试在网页中搜索链接文本,并且如果找不到该项目并移动到其他内容,我正在尝试使程序响应而不会出现错误。

from selenium.common.exceptions import NoSuchElementException

hasElementQ = True
while True:
    try:
        elem = browser.find_element_by_link_text('pant')
        break
        except NoSuchElementException:
            print ('it doesnt exist')

这是我收到的错误:

except NoSuchElementException:
         ^
SyntaxError: invalid syntax

标签: pythonseleniumexceptionselenium-webdrivererror-handling

解决方案


except需要与您的缩进级别相同try

from selenium.common.exceptions import NoSuchElementException

hasElementQ = True
while True:
    try:
        elem = browser.find_element_by_link_text('pant')
        break
    except NoSuchElementException:
        print ('it doesnt exist')

推荐阅读