当我的程序找不到要查找的元素时,发生异常,我想在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."
只需将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] 删除。
我来说两句