这里写自定义目录标题
read方法为什么不能二次读取
from urllib import request,parse
import urllib
#请求头
heard = {
"Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
}
url1 = "https://baidu.com/s?"
name = input('请输入百度内容')
sourse = {
'wd':name
}
url2 = urllib.parse.urlencode(sourse)
url = url1 + url2
res = urllib.request.Request(url = url,headers=heard)
response = urllib.request.urlopen(res)
#打印获取的内容
print(response.read().decode('utf-8'))
#将获取的内容存储到1.html文件中
with open("1.html","w",encoding="utf-8")as f:
f.write(response.read().decode('utf-8'))
上边的程序模拟存在一个问题,1.html文件中没有内容,经过研究发现是因为使用read方法读取数据后指针指向了数据结束位置,因此1.html中没有数据解决这个问题有两个方法:
1.删除print(response.read().decode(‘utf-8’))
2.引入中间变量,将response.read().decode(‘utf-8’)赋值于中间变量,使用中间变量打印和存储获取内容。