浏览器中的编码/解码有效,但在终端中无效
这是我的代码:
import urllib
print urllib.urlopen('http://www.indianexpress.com/news/heart-of-the-deal/811626/').read().decode('iso-8859-1')
当我在Firefox浏览器中查看这个页面时,文字显示得很正常。但是在终端里,我发现字符编码有问题。
以下是一些显示不正常的例子:
long-term in Indias no-go areas
我该怎么解决这个问题呢?
3 个回答
0
这个网页说谎了;它其实是用 cp1252
也就是 windows-1252
编码的,而不是用 ISO-8859-1 编码。
>>> import urllib
>>> guff = urllib.urlopen('http://www.indianexpress.com/news/heart-of-the-deal/811626/').read()
>>> uguff = guff.decode('latin1')
>>> baddies = set(c for c in uguff if u'\x80' <= c < u'\xa0')
>>> baddies
set([u'\x93', u'\x92', u'\x94', u'\x97'])
0
试试这个(忽略不认识的字符)
import urllib
url = 'http://www.indianexpress.com/news/heart-of-the-deal/811626/'
print urllib.urlopen(url).read().decode('iso-8859-1').encode('ascii','ignore')
0
你需要使用服务器实际发送的字符集,而不是总是认为是ISO 8859-1。使用像Beautiful Soup这样的强大HTML解析器会很有帮助。