首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scraperwiki字符编码异常

Scraperwiki字符编码异常
EN

Stack Overflow用户
提问于 2013-05-08 03:28:33
回答 1查看 108关注 0票数 0

这是一个用Python语言编写的ScraperWiki抓取器:

代码语言:javascript
复制
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

它会产生以下输出:

代码语言:javascript
复制
Ecole Polytechnique Federale De Lausanne
Ecole Normale Superieure
Acole Polytechnique
Ecole Normale Superieure De Lyon

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-08 03:53:19

基于soulseekah上面有用的注释,以及lxml文档herehere,下面的解决方案是可行的:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16427010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档