解码用urllib下载的html文件

时间:2016-12-20 12:10:59

标签: python urllib

我尝试下载这样的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

我需要做些什么才能获得正确的编码?

1 个答案:

答案 0 :(得分: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