擅长:python、mysql、java
<p>在Python2中,lxml有时在检查元素的<code>text</code>属性时<a href="http://lxml.de/FAQ.html#why-does-lxml-sometimes-return-str-values-for-text-in-python-2" rel="nofollow">returns ^{<cd1>}s, and sometimes ^{<cd2>}</a>。在</p>
<p>当文本完全由ascii字符组成时,它返回<code>str</code>,否则返回<code>unicode</code>。在</p>
<p>在错误发生的地方,<code>text[0].text</code>是一个<code>unicode</code>,包含字符<code>u'\u0101'</code>。在</p>
<p>要修复此错误,请在打印之前将<code>unicode</code>显式编码为字节字符串:</p>
<pre><code>print(text[0].text.encode('utf-8'))
</code></pre>
<p>注意,<code>utf-8</code>只是众多<a href="https://docs.python.org/2/library/codecs.html#standard-encodings" rel="nofollow">encodings you could use</a>中的一个。在</p>
<hr/>
<p>通常,如果要打印到终端,Python将检测终端使用的编码,并使用该编码对<code>unicode</code>进行编码,从而将字节打印到终端。在</p>
<p>既然你得到了错误</p>
^{pr2}$
<p>您可能正在打印到文件,或者Python无法确定输出设备的编码。由于输出设备只接受字节(从不接受unicode),所以必须对所有unicode进行编码。在这种情况下,Python2会自动尝试使用<code>ascii</code>编解码器对<code>unicode</code>进行编码。因此出现了错误。在</p>
<p>另请参见:<a href="https://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails wiki page</a></p>