问题:
import urllib.request
import sys
resp=urllib.request.urlopen("http://www.baidu.com")
html=resp.read()
fo=open("test.html","w")
fo.write(html)
fo.close()
Python 保存网页,后出现如下错误
解决方法:
import urllib.request
import sys
resp=urllib.request.urlopen("http://www.baidu.com")
html=resp.read()
fo=open("test.html",mode="w",encoding='utf-8')
fo.write(html.decode('utf-8'))
fo.close()
说明
首先因为百度的首页是utf-8编码,但是你读取的html是bytes,字节数组,所以必须转为fo能够write的参数类型,因为bytes已经是utf-8编码的,所以解码decode,
然后,如果你用的是windows的操作系统,默认调用open方法打开的文件编码格式是GBK,
这样默认保存的文件显示在浏览器里面是乱码, 因为你页面内容里面指定的是utf-8编码,就是 content="text/html;charset=utf-8" 这个,但是你html文件编码为GBK,所以直接显示乱码。
只有在你open文件的时候,指定保存的编码格式为utf-8。