我只是在玩urllib2和utf-8页面。在
http://www.columbia.edu/~fdc/utf8/
只获取前700个字节(顶部段)
>>> import urllib2
>>> from urllib2 import HTTPError, URLError
>>> import BaseHTTPServer
>>> opener = urllib2.OpenerDirector()
>>> opener.add_handler(urllib2.HTTPHandler())
>>> opener.add_handler(urllib2.HTTPDefaultErrorHandler())
>>> response = opener.open('http://www.columbia.edu/~fdc/utf8/')
>>> content = response.read(700)
从这里开始,我认为content变量中的字符串应该是utf-8编码的,并且应该显示得很好。在
然而
^{pr2}$似乎html逃过了,所以
>>> import HTMLParser
>>> h = HTMLParser.HTMLParser()
>>> h.unescape(content)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/HTMLParser.py", line 390, in unescape
return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
所以我不明白。 我甚至试过这样做。encode('utf-8')是不可逃避的,但类似的错误。在
从网站上显示utf-8内容的最佳方式是什么?在
您需要将页面从UTF-8解码到Unicode;其中有UTF-8序列(紧挨着非中断空格的HTML实体):
你把编码和解码搞混了;内容已经被UTF-8编码了。在
注意,
^{pr2}$₹
是页面本身的一个错误,;
被省略了。HTML5解析器或浏览器可能会假定可以添加;
,并对其进行解码:必须先用正则表达式修复这些实体:
你误解了你的输出。这里没有HTML编码:但是当您在REPL中简单地输入
content
时,它会显示文本的repr()
-ed版本。在做
print content
会给你带来你想要的:相关问题 更多 >
编程相关推荐