By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,035 Members | 1,555 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,035 IT Pros & Developers. It's quick & easy.

python33, UnicodeEncodeError, how to ignore error

100+
P: 103
I want that my script would continue running despite the error.

Expand|Select|Wrap|Line Numbers
  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
Feb 26 '15 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Encapsulate the offending line in another try/except block.
Feb 26 '15 #2

Expert 100+
P: 619
The first 2 print statements will yield an error because the are not in a try/except. The last print statement will error out for anything other than an IO error. Putting the entire block in a try except will let the code run but may or may not allow you to trace the errors.

Also see this link for the correct use of decode http://www.tutorialspoint.com/python/string_decode.htm (decoding the return value from a print function will not yield anythng useful)
Expand|Select|Wrap|Line Numbers
  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
Feb 26 '15 #3

Post your reply

Sign in to post your reply or Sign up for a free account.