【问题标题】:Parsing letters with macron e.g ā when scraping a web page using lxml使用宏解析字母,例如 ā 使用 lxml 抓取网页时
【发布时间】:2014-08-25 08:48:17
【问题描述】:

尝试解析 Te Reo Maori 中的单词时出现此错误

Pāngarau - 我假设它是宏

UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'\u0101'

关于如何解决这个问题的任何想法?

from lxml import html
import requests

page = requests.get('http://www.nzqa.govt.nz/qualifications-standards/qualifications/ncea/subjects/')
tree = html.fromstring(page.text)

text = tree.xpath('//*[@id="mainPage"]/table[1]/tbody/tr[1]/td[3]/a')

print text[0].text

Traceback(最近一次调用最后一次):

  File "/Users/Teacher/Documents/Python/Standards/rip_html2.py", line 10, in <module>
    print text[0].text
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0101' in position 1: ordinal not in range(128)
[Finished in 0.5s with exit code 1]

【问题讨论】:

  • 请贴出触发此错误的相关代码,无论是lxml相关方法。如果可能的话,也发布回溯。

标签: python parsing lxml


【解决方案1】:

在 Python2 中,当您检查元素的 text 属性时,lxml 有时会出现 returns strs, and sometimes unicode

当文本完全由 ascii 字符组成时返回str,否则返回unicode

在发生错误的地方,text[0].text 是一个包含字符u'\u0101'unicode

要修复错误,请在打印前将unicode 显式编码为字节字符串:

print(text[0].text.encode('utf-8'))

请注意,utf-8 只是众多encodings you could use 之一。


通常,如果您要打印到终端,Python 会检测终端使用的编码,并使用该编码对unicode 进行编码,从而将字节打印到终端。

因为你得到了错误

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

您可能正在打印到文件,或者 Python 无法确定输出设备的编码。由于输出设备只接受字节(从不接受 unicode),所有的 unicode 都必须被编码。在这种情况下,Python2 会自动尝试使用 ascii 编解码器对 unicode 进行编码。因此出现错误。

另见:PrintFails wiki page

【讨论】:

    【解决方案2】:

    这可能是因为 Python 2 默认只支持 ASCII 字符串,除非明确提及。要使用 Unicode 而不是 ASCII,您可以在脚本的第一行添加以下行:

    # -*- coding: utf-8 -*-

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      相关资源
      最近更新 更多