python request 入门

参考:https://www.icourse163.org/learn/BIT-1001870001?tid=1464881473#/learn/content

安装

pip install requests
import requests

Response对象

方法

request()

基础方法

def request(method, url, **kwargs):

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`.
    :return: :class:`Response <Response>` object
    """

head()

def head(url, **kwargs):
    """Sends a HEAD request."""

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.

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
    """

example:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post('http://httpbin.org/post', data = payload)
>>> print(r.text)
{ ...
"form": {
"key2": "value2",
"key1": "value1"
},
}

put()

patch()

delete()

**kwargs:

参数内容
params字典或字节序列,作为参数增加到url中
data字典、字节序列或文件对象,作为Request的内容
jsonJSON格式的数据,作为Request的内容
headers字典,HTTP定制头
cookies字典或CookieJar,Request中的cookie
auth元组,支持HTTP认证功能
files字典类型,传输文件
timeout设定超时时间,秒为单位
proxies字典类型,设定访问代理服务器,可以增加登录认证
allow_redirectsTrue/False,默认为True,重定向开关
streamTrue/False,默认为True,获取内容立即下载开关
verifyTrue/False,默认为True,认证SSL证书开关
cert本地SSL证书路径

异常

异常说明
requests.ConnectionError网络连接错误异常,如DNS查询失败、拒绝连接等
requests.HTTPError HTTP错误异常
requests.URLRequiredURL缺失异常
requests.TooManyRedirects超过最大重定向次数,产生重定向异常
requests.ConnectTimeout连接远程服务器超时异常
requests.Timeout请求URL超时,产生超时异常

Response对象

属性

属性说明
r.status_codeHTTP请求的返回状态
r.textHTTP响应内容的字符串形式,即,url对应的页面内容
r.encoding从HTTP header中猜测的响应内容编码方式
r.apparent_encoding内容中分析出的响应内容编码方式(备选编码方式)
r.contentHTTP响应内容的二进制形式

方法

raise_for_status()

def raise_for_status(self):
        """Raises :class:`HTTPError`, if status_code != 200."""
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值