UnicodeEncodeError - 在Spyder中有效,但在从终端执行时无效

时间:2013-12-17 19:31:29

标签: python string unicode beautifulsoup codec

我正在使用BeautifulSoup解析一些html,Spyder作为我的编辑器(顺便说一下,这两个都是很棒的工具!)。代码在Spyder中运行良好,但是当我尝试从终端执行.py文件时,我收到一个错误:

file =  open('index.html','r')
soup = BeautifulSoup(file)
html = soup.prettify()
file1 =  open('index.html', 'wb')
file1.write(html)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 5632: ordinal not in range(128)

我在Linux服务器上运行OPENSUSE,使用zypper安装Spyder。 有没有人有任何建议可能是什么问题? 非常感谢。

1 个答案:

答案 0 :(得分:1)

那是因为在输出结果之前(即将其写入文件),你必须先编码:

file1.write(html.encode('utf-8'))

查看每个文件都有一个属性file.encoding。引用文档:

  

<强>的file.encoding

     

此文件使用的编码。当Unicode字符串时   写入文件后,它们将被转换为字节串   这种编码。另外,当文件连接到终端时,   该属性给出了终端可能使用的编码   (如果用户配置错误,该信息可能不正确   终奌站)。该属性是只读的,可能并非全部存在   类文件对象。它也可以是None,在这种情况下文件使用   用于转换Unicode字符串的系统默认编码。

看到最后一句话? soup.prettify返回一个Unicode对象,并且出现此错误,我很确定您使用的是Python 2.7,因为它的sys.getdefaultencoding()ascii

希望这有帮助!

相关问题