Skip to main content
 首页 » 编程设计

python之当 xpath = 没有这样的元素时停止循环

2025年05月04日20linjiqin

我试图在未显示 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  

但我得到:

"NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//tbody//tr//td//span//a[text() != ""]"}"

这正是我想要停止循环的时候……当元素不可定位时。

请您参考如下方法:

使用 try block 并从 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 ...