使用urllib下载的HTML文件解码

3

我尝试下载一个像这样的html文件:

import urllib

req  = urllib.urlopen("http://www.stream-urls.de/webradio")
html = req.read()

print html

html = html.decode('utf-16')

print html

由于req.read()之后的输出看起来像是unicode编码,我尝试进行转换,但出现了以下错误:

Traceback (most recent call last):   File
"e:\Documents\Python\main.py", line 8, in <module>
    html = html.decode('utf-16')   
File "E:\Software\Python2.7\lib\encodings\utf_16.py", line 16, in decode
    return codecs.utf_16_decode(input, errors, True) 
UnicodeDecodeError: 'utf16' codec can't decode bytes in position 38-39: illegal UTF-16 surrogate

我需要做些什么来获取正确的编码方式?

好的...你能不能好心告诉我们第38-39位上的字节是什么? - barak manos
顺便说一句,手头的问题与urllib和HTML无关。它只涉及字符编码问题,因此您可能希望重新表述并将问题最小化,以便专注于这个问题,仅此问题。 - barak manos
3
那个页面返回(经过gzip压缩,即不是纯文本)charset=utf-8。你为什么要用utf-16解码? - Alex K.
我部分撤回我的第二条评论。在尝试调查此问题时,具体的URL很重要。 - barak manos
1个回答

3
使用requests,您可以获得正确的、未压缩的HTML。
import requests

r  = requests.get("http://www.stream-urls.de/webradio")
print r.text

编辑:如何使用gzipStringIO在不保存文件的情况下解压缩数据

import urllib
import gzip
import StringIO

req  = urllib.urlopen("http://www.stream-urls.de/webradio")

# create file-like object in memory
buf = StringIO.StringIO(req.read())

# create gzip object using file-like object instead of real file on disk
f = gzip.GzipFile(fileobj=buf)

# get data from file
html = f.read()

print html

“requests” 不是 Python 2.x 内置的包。您能告诉我怎样使用 'pip' 安装它吗? - barak manos
顺便问一下:Python的urllib2模块是否会自动解压从网页获取的gzip数据? - 这个链接展示了如何使用gzip模块来解压服务器返回的数据。 - furas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接