为了账号安全,请及时绑定邮箱和手机立即绑定

Python 中没有错误的中断循环 - Selenium

Python 中没有错误的中断循环 - Selenium

呼啦一阵风 2023-12-29 15:36:08
当我尝试解析循环的最后一页并在下一个 (») 按钮不再存在时退出循环时,出现以下错误: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, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "return-value"))).text        stock_percentage.append(percentage)        price = WebDriverWait(stock, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "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:            breakdriver.quit()请给我一些关于当元素不再存在时如何成功退出循环的指导。谢谢。
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

试试这个:在代码中添加“try”和“ except”函数。使用它们,代码不会返回错误,但会停止。如果你愿意,你可以在出错时重复循环,你只能在 try 结束时放置break。while True: 尝试: #some 代码中断 except: #some 代码



查看完整回答
反对 回复 2023-12-29
  • 1 回答
  • 0 关注
  • 39 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信