在Python中中断循环而没有错误-Selenium

问题描述

当尝试解析循环的最后一页并在下一个(»)按钮不再存在时退出循环时,出现以下错误 selenium.common.exceptions.NoSuchElementException:消息:无法找到元素:»

代码

while True:
    prices = driver.find_element_by_id('showAllGraphsButton')
    prices.click()
    time.sleep(6)
    s_container = driver.find_element_by_id('stockContainer')
    stocks = webdriverwait(s_container,10).until(EC.visibility_of_all_elements_located((By.CLASS_NAME,"imageRow")))
    for stock in stocks:
        name = webdriverwait(stock,10).until(EC.visibility_of_element_located((By.CLASS_NAME,"auto-ellipsis"))).text
        stock_name.append(name)
        percentage = webdriverwait(stock,"return-value"))).text
        stock_percentage.append(percentage)
        price = webdriverwait(stock,"last-price"))).text
        stock_price.append(price)

        if len(driver.find_element_by_link_text('»').text) > 0:
            driver.find_element_by_link_text('»').click()
            time.sleep(6)
        else:
            break

driver.quit()

请为我提供一些有关在元素不再存在时如何成功退出循环的指导。 谢谢。

解决方法

尝试一下:在代码中放入“ try”和“ except”函数。使用它们,代码不会返回错误,但是只会停止。如果需要,可以在出现错误的情况下重复循环,只能在尝试结束时放置中断。 而True: 尝试: #一些代码 打破 除: #一些代码