【问题标题】:Python 2.7.13 UnicodeEncodeError and Special CharactersPython 2.7.13 UnicodeEncodeError 和特殊字符
【发布时间】:2017-08-05 12:25:37
【问题描述】:

我正在编写一个从网站检索信息的简单 python 程序,问题是有些单词包含特殊字符,例如 “°”、“Ψ”等等。

这是我的代码:

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import urllib
r = urllib.urlopen('http://www.samplepage.sample').read()
soup = BeautifulSoup(r, "lxml")
text = soup.find_all("a", class_="some_class")
for word in text:
    word = word.get_text()
    word = word.encode('utf-8')
    print word

输出应该是“°”,但不是那个,而是“°”

如果我尝试使用 ascii 对其进行编码,我会得到经典的 UnicodeEncodeError:

for word in text:
    word = word.get_text()
    word = word.encode('ascii')
    print word

>>> UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-8: 
ordinal not in range(128)

有什么想法吗?

【问题讨论】:

  • 这里的 samplepage.sample 是什么?
  • 任何网页都可以
  • 在您提供 url 之前,我们无法看到您脚本的输出
  • 输出应该是“°”,但我得到的是“°”
  • 我怎么知道输出应该是°Â°

标签: python beautifulsoup ascii encode


【解决方案1】:

这可能是因为您使用错误的编解码器解码字符串。

尝试打印字符串,在使用 utf-8 对其进行编码之前,首先您需要使用正确的编解码器解码字符串。然后你会得到一个 Unicode 对象,你可以打印它并且应该正确显示。

如果它是 ascii 映射之外的特殊字符,则需要 Unicode 对象才能正确显示它。

尝试执行以下操作:

new_word = word.decode('latin-1')
print new_code
word = word.encode('utf-8')

【讨论】:

  • @devmon 我已经在答案中添加了一个 sn-p 供您尝试
猜你喜欢
  • 1970-01-01
  • 2018-09-09
  • 2017-09-06
  • 2015-07-10
  • 2016-10-19
  • 2015-03-10
  • 2014-07-27
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多