You need to enable JavaScript to run this app. Python Selenium捕获NoSuchElementException后如何回到循环继续执行任务
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium捕获NoSuchElementException后如何回到循环继续执行任务

核心问题原因

你当前的try-except结构包裹了整个for循环,只要任意一次迭代触发NoSuchElementException异常,程序就会直接跳出整个循环进入except分支,执行完下一页点击逻辑后就直接结束fakturuj方法,自然无法回到循环继续执行。

修改方案

将try-except挪到for循环内部,同时增加重试逻辑,保证当前找不到的元素在点击下一页后可以重新尝试处理,不会直接跳过当前序号:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import NoSuchElementException
import os


class Bot:
    def __init__(self,username,pw):

        #os.environ['MOZ_HEADLESS'] = '1'
        self.driver = webdriver.Firefox()
        self.driver.maximize_window()
        self.driver.get("https://app.fakturownia.pl/login")
        sleep(1)

        self.driver.find_element_by_xpath("//input[@name='user_session[login]']").send_keys(username)
        self.driver.find_element_by_xpath("//input[@name='user_session[password]']").send_keys(pw)
        self.driver.find_element_by_xpath("//input[@name='commit']").click()

        sleep(1)
        self.driver.get("url")
        sleep(1)
        self.driver.find_element_by_xpath("/html/body/form/div[2]/div[1]/div/div[2]/div/div[2]/a[1]").click()

    def fakturuj(self):
        for faktura in range(2,28):
            # 标记当前序号是否处理完成
            processed = False
            while not processed:
                try:
                    #nr fv
                    self.driver.find_element_by_link_text('{}/06/2021'.format(faktura + 1)).click()
                    #edytuj 1
                    self.driver.find_element_by_xpath('//*[@id="pad-wrapper"]/div[4]/div/nav/div[2]/ul[2]/li[3]/a/span').click()
                    #edytuj 2
                    self.driver.find_element_by_xpath('//*[@id="seller_text"]/label/span').click()
                    #odśwież nr konta
                    self.driver.find_element_by_xpath('//*[@id="update_seller_bank_account_button"]').click()
                    #zapisz
                    self.driver.find_element_by_xpath('//*[@id="invoice_submit_button1"]').click()
                    #返回列表页
                    self.driver.find_element_by_xpath('//*[@id="pad-wrapper"]/div[4]/div/nav/div[2]/ul[1]/li[1]/a').click()
                    # 处理完成,跳出重试循环进入下一个序号
                    processed = True
                    sleep(1)
                except NoSuchElementException:
                    # 找不到元素则点击下一页,继续重试当前序号
                    self.driver.find_element_by_xpath("/html/body/form/div[2]/div[1]/div/div[2]/div/div[2]/a[1]").click()
                    sleep(1)


bot = Bot('mail', 'passw')
bot.fakturuj()

额外优化建议

  • 尽量替换硬编码的sleep为Selenium的显式等待WebDriverWait,可以大幅提升执行效率和稳定性,避免页面未加载完成就触发元素查找逻辑
  • 不要使用绝对路径的XPath定位元素,页面结构稍有变动就会定位失败,优先使用ID、类名、自定义属性等相对定位方式
  • 可增加最大翻页次数限制,避免页面没有下一页时触发死循环

内容的提问来源于stack exchange,提问作者Mikołaj K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 15:27:01