问题描述:
笔者在初学Python爬虫时,用到 urllib.request.urlopen 获取百度搜索页面 (http://www.baidu.com) 上的信息。
首先,访问百度并获取网页信息,将信息保存在 response 中。代码如下:
from urllib.request import urlopen
url = r'http://www.baidu.com'
response = urlopen(url)
然后,调用 .read() 看一下 response 的内容,发现 charset=utf-8,于是用 utf-8 解码。代码如下:
print(response.read())
'''
结果:
b'<!DOCTYPE html><!--STATUS OK-->\n\n\n
<html><head><meta http-equiv="Content-Type" content="text/html;
charset=utf-8">
......'
'''
最后,用 utf-8 解码 response 的内容,并把解码后的内容保存到 百度.html 中。代码如下:
with open(r'百度.html','w') as f:
f.write(response.read().decode('utf-8'))
然而,打开 百度.html 后却发现其一片空白???
现在打印一下 response.read().decode(‘utf-8’),居然也是空的???
print(response.read()