UnicodeDecodeError Python错误

时间:2012-09-15 12:58:26

标签: python unicode

我试图编写一个python google api代码。得到一些unicode问题。到目前为止,我真正基本的PoC是:

#!/usr/bin/env python
import urllib2
from bs4 import BeautifulSoup        
query = "filetype%3Apdf"
url = "http://www.google.com/search?sclient=psy-ab&hl=en&site=&source=hp&q="+query+"&btnG=Search"
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open(url)
data = response.read()
data = data.decode('UTF-8', 'ignore')
data = data.encode('UTF-8', 'ignore')
soup = BeautifulSoup(data)
print u""+soup.prettify('UTF-8')

我的追溯是:

Traceback (most recent call last):
  File "./google.py", line 22, in <module>
print u""+soup.prettify('UTF-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 48786: ordinal not in range(128)

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您正在将soup树转换为UTF-8(编码的字节字符串),然后尝试将其连接到空的u'' unicode 字符串。< / p>

Python将使用默认编码ASCII自动尝试解码您的编码字节字符串,并且无法解码UTF-8数据。

您需要明确解码prettify()输出:

print u"" + soup.prettify('UTF-8').decode('UTF-8')

Python Unicode HOWTO更好地解释了这一点,包括默认编码。我真的,真的建议你也阅读Joel Spolsky的article on Unicode