Python Selenium 如何处理 while loop/if else 语句中的 NoSuchElementException

Python Selenium How to handle NoSuchElementException from while loop/if else statement

我正在尝试编写一个 while 循环,如果找不到元素,它会执行某些任务,但是当找不到元素时,它会抛出错误 NoSuchElementException,就好像没有元素一样,而不是转到 'else' 语句。

elem = driver.find_element_by_id('add-to-bag')

while True:
    if elem.is_displayed():
        False
    else:
        driver.delete_all_cookies()
        driver.refresh()
        sleep(randint(5, 10))

根据您提到的代码块,if an element is found it does certain tasks, however when the element is not found, it throws an error code完美

说明

查找元素的代码就在 while/if 块开始之前。因此,当您的 find_element_by_id('add-to-bag') 失败 而不是返回元素时,它会返回您尚未处理的 NoSuchElementException

解决方案

一个简单的解决方案是为 find_element_by_id('add-to-bag') 引入一个 try-except 块,如下所示:

try :
    elem = driver.find_element_by_id('add-to-bag')
    if elem.is_displayed():
        //implement your logic

except NoSuchElementException :
    driver.delete_all_cookies()
    driver.refresh()
    sleep(randint(5, 10))