python中程序的异常处理_循环中的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."

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值