Python学习之requests的请求方法

requests是用python做自动化必须用到的第三方包,需要自己安装,安装命令为:pip install requests,安装完成后,需要导入方可使用,一般使用requests包下面的get方法和post方法,其他不常用

一、requests中的get方法

get方法源码

def get(url, params=None, **kwargs):
    r"""Sends a GET request.
    :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 \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """
    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

可以看到get方法中的参数url是必须传的,params参数默认为None,如果需要可传,重要的是**kwargs,动态参数kwargs可以传其他参数,如cookie,header,verify等特殊参数
一般get方法用法:

import requests
url = "http://webquotepic.eastmoney.com/GetPic.aspx"
params = {"id":"899001_TB","imageType":"FFRS","token":"44c9d251add88e27b65ed86506f6e5da","type":"FFR"}
r =requests.get(url=url,params=params)
print(r.status_code)
print(r.url)

打印结果为:
在这里插入图片描述

二、requests中的post方法

post方法源码

def post(url, data=None, json=None, **kwargs):
    r"""Sends a POST request.
    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """
    return request('post', url, data=data, json=json, **kwargs)

从源码中可以看出post方法必要的参数也是url,与get方法不同的是post方法的默认参数多了data和json参数,默认都为None,也包含动态参数**kwargs,在使用post方法的时候,如果除了三个默认参数外,其余参数可使用动态参数,如请求为:http://webquest.jbsh.com/GetPic?name=zhulang$age=20,该请求为post方法,参数data={“id”:“52643”,“pg”:“0”},可按照如下方法使用

import requests
url = "http://webquest.jbsh.com/GetPic"
params = {"name":"zhulang","age":"20"}
data ={"id":"52643","pg":"0"}
r =requests.post(url=url,data=data,params=params)
print(r.url)

打印结果
在这里插入图片描述
post方法中data和json有几点需要注意

  1. 当header为Content-Type: application/x-www-form-urlencoded,或者指定用表单传递参数时,此时用data参数,数据格式为:username=zhu&password=123
  2. 当header为’Content-Type’: 'application/json’时,用json传递参数,数据格式为:{“username”: “amy”, “password”: “123”}
  3. 当不指定headers中content-type的类型时,使用data参数传递参数时,content-type默认是:application/json。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值