`
qindongliang1922
  • 浏览: 2147591 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
7265517b-f87e-3137-b62c-5c6e30e26109
证道Lucene4
浏览量:116328
097be4a0-491e-39c0-89ff-3456fadf8262
证道Hadoop
浏览量:124593
41c37529-f6d8-32e4-8563-3b42b2712a50
证道shell编程
浏览量:58457
43832365-bc15-3f5d-b3cd-c9161722a70c
ELK修真
浏览量:70354
社区版块
存档分类
最新评论

Python3.4网页抓取之编码异常

阅读更多
使用Python抓取网页的时候,有时候我们会解析出现异常,这时候,就会导致整个网页解析不成功,究其原因,仅仅是因为编码里某个小小的地方编码出错了,才导致解析失败,那么我们应该如何比较好的避免这种情况出现呢?
看下面的例子:


import urllib.request,urllib.parse,http.cookiejar


cj=http.cookiejar.CookieJar()
opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
opener.addheaders=[('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')]

urllib.request.install_opener(opener)

m=urllib.request.urlopen("http://qindongliang.iteye.com/blog/2142783")



print(m.read().decode('utf-8'))

控制台输出如下:
Traceback (most recent call last):
  File "D:/pythonide/pythonprojectworkspace/python进阶/http学习/tt.py", line 14, in <module>
    print(m.read().decode('utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe6 in position 626: invalid continuation byte

Process finished with exit code 1


当然,我们抓取其他的网页,可能没有这个异常,但是由于某些编码的内容有一些小小的问题,所以导致了上述异常的发生,可以看出是在decode解码时发生的异常,下面我们就看下decode方法的支持的模式,来自python的API文档里面有这样一段话:


codecs.encode(obj, encoding='utf-8', errors='strict') 
Encodes obj using the codec registered for encoding.

Errors may be given to set the desired error handling scheme. The default error handler is strict meaning that encoding errors raise ValueError (or a more codec specific subclass, such as UnicodeEncodeError). Refer to Codec Base Classes for more information on codec error handling.


python默认的解码对待错误的方式是严格执行的,有一点小小错误,就会整个解析失败,当然python也提供了几种其他的错误模式:
序号模式说明
1'strict'只要编码出现错误,就抛出异常
2'replace'使用?等字符替换出现错误编码的地方
3'ignore'忽略出现编码错误的地方,继续解码,并不会抛出任何异常
4'xmlcharrefreplace'用适当的xml字符标记出现问题的地方
5'backslashreplace'使用反斜杠代替出异常字符
6'surrogateescape'使用UPUA标记替代


现在我们加上ignore属性后,又可以正常解析了:




  • 大小: 385.8 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics