Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么有些网站是utf-8有些不是(python)_Python - Fatal编程技术网

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

为什么有些网站是utf-8有些不是(python),python,Python,我使用的是python3.4.3 Mac osx 10.10.4 这是我的代码。当我尝试第一个网站时,我可以得到如下正确的结果: 您可以使用解压缩gzip数据并解码为utf-8: 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('/Us

我使用的是python3.4.3 Mac osx 10.10.4

这是我的代码。当我尝试第一个网站时,我可以得到如下正确的结果:


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

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)
或用于为您执行此操作:

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)

如果你
打印(r.headers)
你可以看到
'content-encoding':'gzip'
来验证数据是gzip,两个网站的字符集都是
utf-8
,区别是一个是gzip,另一个不是。

也许你可以看看这个,谢谢,但是有一个错误,我使用了第一种方法…..UnicodeEncodeError:“ascii”编解码器无法对265-289位置的字符进行编码:序号不在范围(128)@R.hui,我测试了上面的代码,它对我有效,你是否完全按照上面的方法使用它?我在Sublime Text2中运行它,得到了错误,但我在terminal中运行它,它可以工作!您可能希望
encoding=“utf-8”
在打开('/Users/HYN/Desktop/url.txt',w',encoding=“utf-8”)的SublizeWith中编写时,它可以工作。考虑了很多
import requests

r = requests.get(url)

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