【发布时间】:2013-10-30 18:24:22
【问题描述】:
我正在使用 BeautifulSoup 来解析一些网页。
有时我会遇到如下“unicode hell”错误:
在 TheAtlantic.com 上查看本文的来源 [http://www.theatlantic.com/education/archive/2013/10/why-are-hundreds-of-harvard-students-studying-ancient-chinese-philosophy/280356/]
我们在 og:description 元属性中看到了这一点:
<meta property="og:description" content="The professor who teaches Classical Chinese Ethical and Political Theory claims, "This course will change your life."" />
当 BeautifulSoup 解析它时,我看到了:
>>> print repr(description)
u'The professor who teaches\xa0Classical Chinese Ethical and Political Theory claims, "This course will change your life."'
如果我尝试将其编码为 UTF-8 ,就像这条 SO 评论建议的那样:https://stackoverflow.com/a/10996267/442650
>>> print repr(description.encode('utf8'))
'The professor who teaches\xc2\xa0Classical Chinese Ethical and Political Theory claims, "This course will change your life."'
就在我以为我所有的 unicode 问题都在掌控之中的时候,我还是不太明白发生了什么,所以我要提出几个问题:
1- 为什么 BeautifulSoup 会将 &nbsp; 转换为 \xa0 [拉丁字符集空格字符]?此页面上的字符集和标题是 UTF-8,我认为 BeautifulSoup 会提取该数据进行编码?为什么不替换为 <space> ?
2- 有没有一种通用的方法来规范化空格以进行转换?
3- 当我编码为 UTF8 时,\xa0 在哪里变成了\xc2\xa0 的序列?
我可以通过unicodedata.normalize('NFKD',string) 传递所有信息,以帮助我到达我想去的地方——但我很想了解哪里出了问题并避免将来出现此类问题。
【问题讨论】:
标签: python unicode beautifulsoup