urllib.request.urlopen()方法发送一个get请求到服务器,服务器返回一个HTTPResponse对象,这个HTTPResponse对象即是服务器的响应报文。下例讲述获取HTTPResponse对象包含的具体内容。
from urllib import request
with request.urlopen('https://www.baidu.com') as f:#urlopen函数返回一个HTTPResponse对象,赋给f
data=f.read()#读取f所有内容,赋给data
print('f:==================')
print(f)
print(type(f))# <class 'http.client.HTTPResponse'>
# 获取HTTP协议版本号
print(f.version)
# 获取响应码
print(f.status)
print(f.getcode())
# 获取响应描述字符串
print(f.reason)
# 获取实际请求的页面url(防止重定向用)
print(f.geturl())
#获取响应头信息,返回二元元组列表
print(f.getheaders())
for k,v in f.getheaders():
print('%s:%s'% (k,v))
#获取特定响应头信息
print(f.getheader(name='Content-Type'))
# 获取响应头信息,返回字符串
print(f.info())
print('==================')
# 获取响应体
print(f.readline().decode('utf-8'))
print('Data:',data.decode('utf-8'))
参考资料:
HTTPResponse对象的用法总结:https://blog.csdn.net/topleeyap/article/details/78845946
http响应报文结构:https://blog.51cto.com/12805107/2067971
python urllib模块发送http请求方法:https://www.liaoxuefeng.com/wiki/1016959663602400/1019223241745024