循环中的Python异常处理

瑞安·杜利(Ryan Dooley)

当我的程序找不到要查找的元素时,发生异常,我想在CSV中记录事件,显示一条消息,指出发生错误并继续。我已成功将事件记录到CSV中并显示消息,然后程序跳出循环并停止。我如何指示python继续。请检查我的代码。

sites = ['TCF00670','TCF00671','TCF00672','TCF00674','TCF00675','TCF00676','TCF00677']`

with open('list4.csv','wb') as f:
    writer = csv.writer(f)
    try:
        for s in sites:
            adrs = "http://turnpikeshoes.com/shop/" + str(s)
            driver = webdriver.PhantomJS()
            driver.get(adrs)
            time.sleep(5)
            LongDsc = driver.find_element_by_class_name("productLongDescription").text
            print "Working.." + str(s)
            writer.writerows([[LongDsc]])
    except:
        writer.writerows(['Error'])
        print ("Error Logged..")
        pass

    driver.quit()
print "Complete."
埃利·科维戈(Eli Korvigo)

只需将try/except块放入循环中即可。并且pass在该except的末尾不需要该语句

with open('list4.csv','wb') as f:
    writer = csv.writer(f)
    for s in sites:
        try:
            adrs = "http://turnpikeshoes.com/shop/" + str(s)
            driver = webdriver.PhantomJS()
            driver.get(adrs)
            time.sleep(5)
            LongDsc = driver.find_element_by_class_name("productLongDescription").text
            print "Working.." + str(s)
            writer.writerows([[LongDsc]])
        except:
            writer.writerows(['Error'])
            print ("Error Logged..")

注意如果except没有特定的异常类,通常是不好的做法,例如,您应该这样做except Exception:...

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

循环中的Python异常处理

来自分类Dev

在while循环中处理异常

来自分类Dev

在while循环中处理异常

来自分类Dev

在异步循环中处理超时异常

来自分类Dev

for循环中的异常行为

来自分类Dev

如何在Python中的线程循环中引发异常?

来自分类Dev

do while循环中的异常

来自分类Dev

while循环中的异常行为

来自分类Dev

循环处理多个异常

来自分类Dev

while循环与异常处理

来自分类Dev

循环处理异常

来自分类Dev

Python:处理无值的Attrgetter可以在循环中使用

来自分类Dev

如何处理for循环中的错误(python)并继续执行

来自分类Dev

在python的循环中保存Excel文件时的多处理

来自分类Dev

如何在for循环中使用多重处理-Python

来自分类Dev

如何在python for循环中应用多处理技术?

来自分类Dev

正确的 Python 方法:在 for 循环中处理原始文件

来自分类Dev

循环中处理语句错误

来自分类Dev

Foreach 循环中的并行处理

来自分类Dev

For循环中的Python列表

来自分类Dev

Python:在for循环中

来自分类Dev

循环中的Python行为

来自分类Dev

循环中的python变量

来自分类Dev

Python - 在 for 循环中屏蔽?

来自分类Dev

Junit循环处理预期的异常

来自分类Dev

for循环中的整数溢出导致异常行为

来自分类Dev

Java While循环中的VariableDeclaratorID异常

来自分类Dev

在“ for”循环中在哪里捕获异常?

来自分类Dev

如何忽略循环中的异常并继续执行