简体   繁体   English

循环中的 Python 异常处理

[英]Python Exception Handling with in a loop

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.当我的程序找不到它要查找的元素时会发生异常,我想在 CSV 中记录事件,显示发生错误的消息并继续。 I have successfully logged the event in the CSV and display the message, Then my program jumps out of the loop and stops.我已成功将事件记录在 CSV 中并显示消息,然后我的程序跳出循环并停止。 How can I instruct python to continue.我如何指示 python 继续。 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."

Just put the try/except block inside the loop.只需将try/except块放入循环中即可。 And there is no need in that pass statement at the end of the except block.并且不需要在except块末尾的pass语句中。

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, eg you should do except Exception:...注意在没有特定异常类的情况下使用except通常是一种不好的做法,例如,您应该使用except Exception:...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM