Python 如何在selenium中找不到项时引发错误并转到其他函数

Python 如何在selenium中找不到项时引发错误并转到其他函数,python,selenium,exception,selenium-webdriver,error-handling,Python,Selenium,Exception,Selenium Webdriver,Error Handling,我正在尝试搜索网页中的链接文本,如果找不到该项目,我将尝试使程序无错误地响应,并转移到其他内容 from selenium.common.exceptions import NoSuchElementException hasElementQ = True while True: try: elem = browser.find_element_by_link_text('pant') break except NoSuchElement

我正在尝试搜索网页中的链接文本,如果找不到该项目,我将尝试使程序无错误地响应,并转移到其他内容

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

您的
除外
需要与您的
尝试处于相同的缩进级别

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')

请正确设置代码的格式,尤其是因为这是一个语法错误。要设置代码的格式,您必须标记代码(选择它),然后按ctrl+k,或者在每行的大号中添加4个空格,必须保存代码中的本机缩进。另外,请阅读有关缩进的内容: