最近爬取,或者解析网页是总是遇到编码问题(我的版本:python2.7)

一、常见异常:UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 0: ordinal not in range(128)

常见解决方案:在代码头添加如下文件

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

有时也会遇到字符转换的问题:

>>> str(u'')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u6211' in position 0: ordinal not in range(128)

解决方法如下:

>>> str(u''.encode('utf-8'))
'\xe6\x88\x91'

二、在爬取网页进行解析的时候,遇到中文需要存储的,一般要先看一下中文是什么格式的,如果是unicode则需要进行转码

xx = xxx.encode('utf-8')
f.write(xx)

 

注:以上解决方案有所借鉴其他博友,未能找到源博

相关文章:

  • 2022-01-17
  • 2021-09-01
  • 2022-01-07
  • 2021-12-18
  • 2021-11-09
  • 2022-12-23
  • 2021-08-24
  • 2021-06-06
猜你喜欢
  • 2021-11-29
  • 2021-05-17
  • 2022-01-26
  • 2022-12-23
  • 2022-12-23
  • 2021-05-06
  • 2021-05-01
相关资源
相似解决方案