最近用Python写了些爬虫,在爬取一个gb2312的页面时,抛出异常:

  1. UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-23: ordinal not in range(128)

解决UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position

解决方案如下:

首先设置系统的默认编码为utf-8:

  1. import sys
  2.  
  3. reload(sys)
  4. sys.setdefaultencoding('utf-8')

然后将网页以gbk解码后转为utf-8:

  1.         result = urllib2.urlopen(req).read()
  2.         result = unicode(result,'GBK').encode('UTF-8')

之后就正常了。

相关文章:

  • 2022-02-08
  • 2022-01-24
  • 2021-08-14
  • 2021-12-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-06
  • 2021-10-23
  • 2022-01-20
  • 2022-12-23
相关资源
相似解决方案