【问题标题】:Scraperwiki character encoding anomalyScraperwiki 字符编码异常
【发布时间】:2013-05-07 19:28:32
【问题描述】:

这是一个用 Python 编写的 ScraperWiki 爬虫:

import lxml.html
import scraperwiki
from unidecode import unidecode

html = scraperwiki.scrape("http://www.timeshighereducation.co.uk/world-university-rankings/2012-13/world-ranking/range/001-200")
root = lxml.html.fromstring(html)
for tr in root.cssselect("table.ranking tr"):
    if len(tr.cssselect("td.rank")) > 0 and len(tr.cssselect("td.uni")) > 0:
        university = unidecode(tr.cssselect("td.uni")[0].text_content()).strip().title()
        if 'cole' in university:
            print university

它产生以下输出:

Ecole Polytechnique Federale De Lausanne
Ecole Normale Superieure
Acole Polytechnique
Ecole Normale Superieure De Lyon

我的问题:是什么导致第三个输出行上的初始字符呈现为“A”而不是“E”,我该如何阻止这种情况发生?

【问题讨论】:

  • 以 Ecole 的形式出现的和以 Acole 的形式出现的是有区别的。 Ecole 的实际上是 École,而突出的是 École Polytechnique,即不是 HTML 实体。中断可能发生在lxmlunidecode 中。还要确保您的终端支持正确的编码。
  • 没错。奇怪的是,Firefox 检查器没有显示出这种差异。现在尝试找出解决方案。顺便说一句,如果你想把你的评论变成一个答案,我很乐意投票(如果它回答了我问题的第二部分,那么我当然也很乐意将它标记为已解决)。

标签: python unicode python-unicode scraperwiki


【解决方案1】:

根据上述soulseekah 的有用评论以及lxml 文档herehere,以下解决方案有效:

import lxml.html
import scraperwiki
from unidecode import unidecode
from BeautifulSoup import UnicodeDammit

def decode_html(html_string):
    converted = UnicodeDammit(html_string, isHTML=True)
    if not converted.unicode:
        raise UnicodeDecodeError(
            "Failed to detect encoding, tried [%s]",
            ', '.join(converted.triedEncodings))
    return converted.unicode

html = scraperwiki.scrape("http://www.timeshighereducation.co.uk/world-university-rankings/2012-13/world-ranking/range/001-200")
root = lxml.html.fromstring(decode_html(html))
for tr in root.cssselect("table.ranking tr"):
    if len(tr.cssselect("td.rank")) > 0 and len(tr.cssselect("td.uni")) > 0:
        university = unidecode(tr.cssselect("td.uni")[0].text_content()).strip().title()
        if 'cole' in university:
            print university

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    相关资源
    最近更新 更多