我正在使用 BeautifulSoup 来解析一些网页。
有时我会遇到如下“unicode hell”错误:
在 TheAtlantic.com 上查看这篇文章的来源 [http://www.theatlantic.com/education/archive/2013/10/why-are-hundreds-of-harvard-students-stuying-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 ,就像这个评论建议的那样: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要转换
to \xa0
[拉丁字符集空格字符]?此页面上的字符集和标题是 UTF-8,我认为 BeautifulSoup 会提取该数据进行编码?为什么不将其替换为<space>
?
2-是否有一种通用的方法来规范转换的空格?
3-当我编码为 UTF8 时,在哪里\xa0
成为序列\xc2\xa0
?
我可以通过管道传输一切unicodedata.normalize('NFKD',string)
帮助我到达我想去的地方 - 但我很想了解问题所在并避免将来出现类似问题。