python33,UnicodeEncodeError,如何忽略错误

我希望我的脚本将继续运行,尽管有错误。

选择 | 换行 | 行号
  1. fw=open(fname,'r',encoding='utf-8')
  2. bhtml=str(fw.readlines())
  3. soup=BeautifulSoup(bhtml)
  4. for tagdiv in soup.find_all("div", class_="hw_txt"):
  5.     word=tagdiv.get_text()
  6.     print(" replace word=",repr(word)) #gives error, interrupts script
  7.     print(" replace word=",word ).decode("utf-8","ignore")  #gives error, interrupts script
  8.     try:
  9.         print(" replace word=",word)
  10.     except IOError:
  11.         pass
  12.     #gives error, interrupts script
# 回答1


将有问题的行封装在另一个try/Except块中。
# 回答2


前两条print语句将产生错误,因为它们不在try/Except中。除IO错误外,最后一条打印语句将出现任何错误。将整个代码块放在一次尝试中,但会让代码运行,但可能允许也可能不允许跟踪错误。
另请参阅此链接了解DECODE的正确用法
Http://www.tutorialspoint.com/python/string_decode.htm
(对打印函数的返回值进行解码不会产生任何有用的结果)

选择 | 换行 | 行号
  1. import traceback
  2.  
  3. try:
  4.     fw=open(fname,'r',encoding='utf-8')
  5.     bhtml=str(fw.readlines())
  6.     soup=BeautifulSoup(bhtml)
  7.     for tagdiv in soup.find_all("div", class_="hw_txt"):
  8.         word=tagdiv.get_text()
  9.         print(" replace word=",repr(word))
  10.         print(" replace word=",word ).decode("utf-8","ignore")
  11.         print(" replace word=",word)
  12. except:
  13.     traceback.print_exc()
  14. ##    raise  ## uncomment to cause the program to stop on an error

标签: python

添加新评论