问题描述:
笔者在初学Python爬虫时,用到 urllib.request.urlopen 获取百度搜索页面 (http://www.baidu.com) 上的信息。
首先,访问百度并获取网页信息,将信息保存在 response 中。代码如下:
from urllib.request import urlopen
url = r'http://www.baidu.com'
response = urlopen(url)
然后,用 utf-8 解码 response 的内容,并把解码后的内容保存到 百度.html 中。代码如下:
with open(r'百度.html','w') as f:
f.write(response.read().decode('utf-8'))
然而,打开 百度.html 后却发现中文乱码???
解决方案:
只需要将要写入的 html 的 encoding 设置为 utf-8 即可。代码如下:
with open(r'百度.html',mode='w',encoding='utf-8') as f:
f.write(response.read().decode('utf-8'))
经过上述修改,就能使 要写入的文件 百度.html 以及 要写入的内容response.read().decode(‘utf-8’) 的编码都是 utf-8。
如有不当之处,烦请指出!