Python 2.7.13 UnicodeEncodeError 和特殊字符

Python 2.7.13 UnicodeEncodeError and Special Characters

我正在编写一个简单的 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)

有什么想法吗?

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

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

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

尝试执行以下操作:

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