首页 > python保存网页到本地出错

python保存网页到本地出错

python代码:

import urllib.request
resp=urllib.request.urlopen('http://www.baidu.com')
html=resp.read()

file_object = open("test.txt","w")
file_object.write(html)  
file_object.close()

报错:

Traceback (most recent call last):
  File "D:\Code\Python\test\study.py", line 6, in <module>
    file_object.write(html)
TypeError: must be str, not bytes

哥们,Not say how old are you!
参考代码

import urllib.request
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。

供参考。


python3.0跟2.7还是有挺大差别啊。

难怪楼主发urllib.request 没用过呢。。。

平时 写2.7, 用的是urllib和urlrlib2库

【热门文章】
【热门文章】