【问题标题】:Python selenium error handlingPython 硒错误处理
【发布时间】:2016-09-13 09:08:58
【问题描述】:

我有一个 python selenium 脚本,它通过这样的循环运行......

for i, refcode in enumerate(refcode_list):

    try:
        source_checkrefcode()
    except TimeoutException:
        pass
        csvWriter.writerow([refcode, 'error', timestamp])

如果在 source_checkrefcode 期间出现问题,则脚本会因错误而崩溃。

如何向此循环添加错误处理,使其仅移动到下一项而不是崩溃?

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    您可以添加检查异常消息,以下是示例代码以供您理解。

    for i, refcode in enumerate(refcode_list):
        try:
            source_checkrefcode()
        except Exception as e:
            if 'particular message' in str(e):
                # Do the following
                # if you don't want to stop for loop then just continue
                continue
    

    【讨论】:

    • 我的原始代码会查找 TimeoutException,但您的示例使用了异常。这个新代码还会捕获 TimeoutException 吗?
    • 是的,实际上 Exception 会捕获所有类型的异常。然后,您可以对其字符串消息添加检查。例如。如果 str(e) 中的“TimeountException”:执行此操作 elif str(e) 中的“另一个异常”:执行此操作,依此类推
    【解决方案2】:

    我同意哈桑的回答。但是如果你使用 continue ,那么你将不会处理任何其他代码块。

    for i, refcode in enumerate(refcode_list):
        try:
            source_checkrefcode()
        except Exception as e:
            if 'particular message' in str(e):
                # Do the following
                # if you don't want to stop for loop then just continue
                continue
        # another code of block will skip. Use pass or continue as per your requirement.
    

    你必须明白 pass 和 continue 之间的区别 Link

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多