处理响应消息
检查HTTP响应的状态码
直接通过reponse对象的status_code属性获取
import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.status_code)
200
检查响应消息头
检查HTTP响应的消息头,直接通过response对象的headers属性获取
如果是想要取出一个元素的值:print(response.headers['Content-Type'])
检查响应消息体
若想获取响应消息体的文本内容,直接通过response对象的text属性来获取
import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.text)
字节串 -> 字符串 ;那么requests库是以什么编码格式把HTTP响应消息体中的字节串解码为字符串的呢 ?
—— 通常requests会根据响应消息头(比如Content-Type) 对编码格式进行推测,(Content-Type:text/html ; charset = utf-8 就是指定文本格式为html , 编码格式为utf-8)但有时候,服务端不一定会在消息头中指定编码格式,就会导致推测有误,就需要我们指定编码格式
import requestsresponse = requests.get('http://mirrors.sohu.com/')
response.encoding='utf8'
print(response.text)
如果想要直接获取消息体中字节串的内容,可采用content属性
import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.content)
如果想转换成字符串
import requestsresponse = requests.get('http://mirrors.sohu.com/')
print(response.content)