循环中的Python异常处理

时间:2016-07-08 16:21:32

标签: python csv error-handling exception-handling

当我的程序找不到要查找的元素时发生异常,我想在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."

1 个答案:

答案 0 :(得分:4)

只需将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:...