python - 为什么有些网站是 utf-8 有些不是 (python)

标签 python

import urllib.request

#url="http://www.fafu.edu.cn"
url="http://www.zhihu.com"
m=urllib.request.urlopen(url).read()
#m.decode("utf-8").encode('')
f=open('/Users/HYN/Desktop/url.txt','wb')
f.write(m)
f.close()
#print(m)

我正在使用 python3.4.3 Mac osx 10.10.4

这是我的代码。当我尝试第一个网站时,我可以得到这样正确的东西:

<link rel="stylesheet" type="text/css" href="/page/main151/style.css" />

<style type="text/css">
<!--
body {font-size:9pt}
td {font-size:9pt}
-->
</style>
<style TYPE="text/css">
<!--
A:link{text-decoration:none; color:#000000}
A:visited{text-decoration:none; color:#000000}
A:hover {color: #ff00ff;text-decoration:underline}
 
#bar a:link {font-size: 10.5pt; font-weight: 700
}
#bar a:visited {font-size: 10.5pt; font-weight: 700
}
#bar a:hover {font-size: 10.5pt; font-weight: 700
}

但是当我尝试第二个网站时,我只能得到这个:

1f8b 0800 4e8b c055 02ff ed3c 6b73 d456
96df f32b 14cd 546a a70a b9f5 7e10 eca9
541e 3599 5466 c84e b676 b3a9 94eb 4aba
722b 744b 8da4 f683 a9ad 0236 010c 06c2
f0c8 069c 00d9 1098 2418 4fb2 09c6 364e
d5fe 95b4 badb 9ff8 0b7b ae5e ad7e 896e
db24 ec30 1476 bbaf ce3d e7de 73cf f3de
7375 e0f9 57fe f8f2 dbef 1c7c 952a 07d5
cad4 7307 c807 5541 cecc 247d a4cc bcfc
079a b461 64c2 4715 0788 32ca c8f3 7130
49d7 038b 51e9 b4d9 4155 3c49 a35a ad82
193b a83b d867 e00b 4d19 ae13 6027 881e
31b6 3929 0a3c af88 82ca 663d cb41 5063
f0e1 ba3d 3b49 ff1b f32f 2f31 2fbb d51a
0a6c bd82 73dd 5f7f 7512 9b33 789f 51f6
5ca0 c4d1 54a9 9bb4 871d 137b d8cb f599
c3fa 213b e883 34b1 6f78 762d b05d 2707
dc58 3bda 58fb aab5 7c3d 5cf9 ac75 f583
d6c3 0bad 8de5 ed8f 575a 772f b5be d80a
97d6 1f6d 2e85 6b2b e1e9 bf36 1ede 08ef

我怎样才能得到正确的东西?

最佳答案

您可以使用 gzip解压缩 gzipped 数据并解码为 utf-8:

import gzip
m = urllib.request.urlopen(url,).read()
data = gzip.decompress(m).decode("utf-8")
with open('/Users/HYN/Desktop/url.txt','w') as f:
    f.write(data)

或者使用requests为你做:

import requests

r = requests.get(url)

data = r.content.decode("utf-8")

如果您print(r.headers),您可以看到'content-encoding': 'gzip' 以验证数据是否已压缩,两个网站的字符集都是utf-8,区别在于一个是压缩的,另一个不是。

关于python - 为什么有些网站是 utf-8 有些不是 (python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31806482/

相关文章:

Python读取csv文件,并跳过非固定长度的 header 部分

python - 使用Python SQLite3在列中查找拉丁字母

python - 有条件地格式化 Python pandas 单元格

python - 如何授权 django-rest-knox 登录路径而不出现 401 错误?

python - apache2 上的 python 出现 404 错误

python - 为什么在 Keras 中尝试构建具有多个输入的架构时会出错?

python - 为什么 a**2 != a * a 对于一些花车?

python - 如何折叠/累积一个 numpy 矩阵乘积(点)?

Python局部变量初始化

python - 我想查找列表的总计,但出现错误