requests模块01
文章目录
一、 requests模块介绍
网址: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
1、requests模块的作用
发送http请求,获取响应数据
二、response.text和response.content的区别
response.text
-
类型: str
-
解码类型: requests模块自动根据HTTP头部对响应的编码作出有根据的推测,推测的文本编码
response.content
-
类型: bytes
-
解码类型:没有指定
import requests
url =' http://www.baidu.com'
response = requests.get(url)
response.encoding='utf8'
print(response.text)
print(response.encoding)
三、通过对response.content进行decode,来解决中文乱码
response -content.decode(默认utf-8
response.content.decode( “GBK”)
·常见的编码字符集
- utf-8
- gbk
- gb2312入
- ascii(读音:阿斯克码)
- iso-8859-1
四、response响应对象的其它常用属性或方法
response = requests.get(url)中response是发送请求获取的响应对象;
response响应对象中除了text、content获取响应内容以外还有其它常用的属性或方法:
- response.ur1响应的url;有时候响应的url和请求的url并不一致response .status_code响应状态码
- response.request.headers响应对应的请求头response.headers响应头
- response.request._cookies响应对应请求的cookie;返回cookieJar类型
- response.cookies响应的cookie(经过了set-cookie动作;返回cookieJar类型
- response.json()自动将json字符串类型的响应内容转换为python对象(dict or list)
import requests
url =' http://www.baidu.com'
response = requests.get(url)
print(response.url)
print(response.status_code)
import requests
url =' http://www.baidu.com'
response = requests.get(url)
print(response.request.headers)
print(response.headers)
import requests
url =' http://www.baidu.com'
response = requests.get(url)
print(response.cookies)