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()方法,使用该方法,可以更方便的封装,和维护

官方定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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就是对于的请求方法;

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

1
2
3
4
5
6
7
8
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 @   袁小文子  阅读(1583)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示