循环中的Python异常处理 [英] Python Exception Handling with in a loop

查看:292
本文介绍了循环中的Python异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

An exception occurs when my program can't find the element its looking for, I want to log the event within the CSV, Display a message the error occurred and continue. I have successfully logged the event in the CSV and display the message, Then my program jumps out of the loop and stops. How can I instruct python to continue. Please check out my code.

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."


推荐答案

只需将 try /循环内的块除外。在除外块的末尾,不需要$ pass 语句。

Just put the try/except block inside the loop. And there is no need in that pass statement at the end of the except block.

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..")

注意使用通常是一个坏习惯,除了没有特定的异常类,例如您应该执行例外:...

NOTE It's generally a bad practice to use except without a particular exception class, e.g. you should do except Exception:...

这篇关于循环中的Python异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆