我试图下载这样一个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我该怎么做才能得到正确的编码?
发布于 2016-12-20 12:27:16
使用请求,您就可以得到正确的、未压缩的HTML。
import requests
r = requests.get("http://www.stream-urls.de/webradio")
print r.text编辑:如何在不保存文件的情况下使用gzip和StringIO压缩数据
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 htmlhttps://stackoverflow.com/questions/41242070
复制相似问题