在xpath = no这样的元素时停止循环

Jag*_*agr 1 python selenium for-loop while-loop

我试图在没有显示xpath时停止while循环.但是,代码会停止并显示NoSuchElementException消息.这是我的代码,

 n=1
    while n<100:


        n+=1
        time.sleep(10)

#       

        Data=driver.find_element_by_xpath('.//tbody//tr//td//span//a[text() != ""]').is_displayed()

        if Data == True:

           ...

       if Data == False: 
           break 
Run Code Online (Sandbox Code Playgroud)

但我得到了:

"NoSuchElementException:消息:没有这样的元素:无法定位元素:{"method":"xpath","selector":".// tbody // tr // td // span // a [text()!= ""] "}"

这正是我想要停止循环...当元素不可定位时.

r.o*_*ook 5

使用try块并从中导入例外selenium.

from selenium.common.exceptions import NoSuchElementException

...

while n<100:

   ...

   try:
        Data=driver.find_element_by_xpath('.//tbody//tr//td//span//a[text() != ""]').is_displayed()
   except NoSuchElementException:
        break

   ... rest of code ...
Run Code Online (Sandbox Code Playgroud)