python request模块的基本使用

一 获取响应数据

1/如果没有安装该模块的话,需要先安装该模块,pip install requests

2/导入该模块

3/就可以正常使用了

import requests

url='http://www.baidu.com'
response=requests.get(url)
# 获取响应信息的状态码
print(response.status_code)
# 获取响应头
print(response.headers)

# 获取返回信息方式
# 1/获取返回信息,自动识别返回信息的编码并进行解码(可能会有乱码)
print(response.text)
# 2/对返回内容用指定的编码格式进行解密
print(response.content.decode('utf-8'))
# 3/使用requests模块里的json()方法对返回内容进行解码(只有返回格式时json时使用,其他编码格式使用会报错)
print(response.json())

4/可以看到,使用requests模块的一些属性,就可以获取到对应的值,如获取响应码,响应头等;

而获取返回信息时,方法3是使用的该模块的方法json()来获取json返回格式的响应信息;

 

二,获取请求数据

# 获取请求头
print(response.request.headers)
# 获取请求体
print(response.request.body)
# 响应头信息,字典类型
print(response.headers)

 

 

三、requests 模块中post方法的使用

3.1当参数类型为:

 Content-Type:application/x-www-form-urlencoded

此类型是表单类型的参数,这时使用post函数时,用data这个关键字参数;

url='https://passport.baidu.com/v2/api/?login'

# 请求方法: POST
params={
    'username': 'name',
    'password': 'password'
}
response=requests.post(url=url,data=params)

3.2 参数类型为:content-type:   application/json

json类型的参数,使用post函数时,用json这个关键字参数

url1='https://passport.csdn.net/v1/register/pc/login/doLogin'
params={
    'loginType': "1",
    'pwdOrVerifyCode': "password",
    'userIdentification': "username"
}
reponse=requests.post(url=url1,json=params)

 

四、requests.request()方法,使用该方法,可以更方便的封装,和维护

官方定义如下:

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:return: :class:`Response <Response>` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'https://httpbin.org/get')
      >>> req
      <Response [200]>
    """

 用法和requests模块里的get及post请求方法一样,只不过requests.request(method,url,**kwargs),method就是对于的请求方法;

为了对比说明,我们可以看下面的一段伪代码

    def test_add(self):
        url='xxxx'
        params='xxxxx'
        method='get'
        # 方法1:用requests.request()方法来实现
        res=requests.request(method=method,url=url,json=params)
        # 方法2:用get方法来实现
        res2=requests.get(url=url,json=params)

  如果分别用方法1和方法2来运行,结果res和res2是一样的;

 

posted @ 2022-08-18 16:58  袁小文子  阅读(1629)  评论(0)    收藏  举报