保存网页TypeError: must be str, not bytes
来源:互联网 发布:华为智能家庭软件 编辑:程序博客网 时间:2024/06/05 18:33
问题:
import urllib.requestimport sysresp=urllib.request.urlopen("http://www.baidu.com")html=resp.read()fo=open("test.html","w")fo.write(html)fo.close()
Python 保存网页,后出现如下错误
解决方法:
import urllib.requestimport sysresp=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。
0 0
- 保存网页TypeError: must be str, not bytes
- TypeError: must be str, not bytes
- TypeError: must be str, not bytes
- Python中报错TypeError: must be str, not bytes
- TypeError: the JSON object must be str, not 'bytes'
- TypeError: write() argument must be str, not bytes
- docx2txt TypeError: write() argument must be str, not bytes
- python3-网络编程-TypeError: send() argument 1 must be bytes or buffer, not str异常
- Python出现TypeError: file() argument 1 must be encoded string without NULL bytes, not str问题解决
- Python 读写文件 中文乱码 错误TypeError: write() argument must be str, not bytes+
- python提示错误TypeError: write() argument must be str, not bytes
- Python 读写文件 错误TypeError: write() argument must be str, not bytes+
- 关于TypeError: strptime() argument 1 must be str, not bytes解析
- write() argument must be str, not bytes
- 使用pickle将对象存储到文件中时出现 TypeError: write() argument must be str, not bytes
- TypeError: expected bytes, not str
- python-TypeError: write() argument must be str, not numpy.float64
- TypeError: the JSON object must be str, not 'TextIOWrapper'
- no project are available for deployment to this server&n
- Java内存泄露
- CCS 6.0.1 断点(取消后一直存在)及底层代码问题
- eclipse一闪而过 启动失败
- Windows10 如何会成为微软的新起点?
- 保存网页TypeError: must be str, not bytes
- js运动框架完美运动框架
- Activity间的数据传递
- zoj3299 Fall the Brick
- Windows10 如何会成为微软的新起点?
- Objective-c NSMutableData和NSData常用操作
- python游戏:兔子与獾
- Job found still running after platform shutdown. Jobs should be canceled by the plugin that sched
- C#实现打印与打印预览功能