zoukankan      html  css  js  c++  java
  • requests模块--python发送http请求

    requests模块

            在Python内置模块(urllib、urllib2、httplib)的基础上进行了高度的封装,从而使得Pythoner更好的进行http请求,使用Requests可以轻而易举的完成浏览器可有的任何操作。Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库。


    requests使用

    一、GET请求

    向 https://github.com/timeline.json 发送一个GET请求,将请求和响应相关均封装在 ret 对象中。

    1、无参数实例

    1
    2
    3
    4
    5
    6
    import requests
      
    ret = requests.get('https://github.com/timeline.json')
      
    print ret.url
    print ret.text

    2、有参数实例

    1
    2
    3
    4
    5
    6
    7
    import requests
      
    payload = {'key1': 'value1', 'key2': 'value2'}
    ret = requests.get("http://httpbin.org/get", params=payload)
      
    print ret.url
    print ret.text

    二、POST请求

    向https://api.github.com/some/endpoint发送一个POST请求,将请求和相应相关的内容封装在 ret 对象中。

    1、基本POST实例

    1
    2
    3
    4
    5
    6
    import requests
      
    payload = {'key1': 'value1', 'key2': 'value2'}
    ret = requests.post("http://httpbin.org/post", data=payload)
      
    print ret.text


    2、发送请求头和数据实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import requests
    import json
      
    payload = {'some': 'data'}
    headers = {'content-type': 'application/json'}
      
    ret = requests.post(url, data=json.dumps(payload), headers=headers)
      
    print ret.text
    print ret.cookies


    3、其他请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    requests.get(url, params=None, **kwargs)
    requests.post(url, data=None, json=None, **kwargs)
    requests.put(url, data=None, **kwargs)
    requests.head(url, **kwargs)
    requests.delete(url, **kwargs)
    requests.patch(url, data=None, **kwargs)
    requests.options(url, **kwargs)
      
    # 以上方法均是在此方法的基础上构建
    requests.request(method, url, **kwargs)


    更多参数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    def request(method, url, **kwargs):
        """Constructs and sends a :class:`Request <Request>`.
     
        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
        :param data: (optional) Dictionary, 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 headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
        :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
        :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long to wait for the server to send data
            before giving up, as a float, or a :ref:`(connect timeout, read
            timeout) <timeouts>` tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
        :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
        :param stream: (optional) if ``False``, the response content will be immediately downloaded.
        :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
        :return: :class:`Response <Response>` object
        :rtype: requests.Response
     
        Usage::
     
          >>> import requests
          >>> req = requests.request('GET', 'http://httpbin.org/get')
          <Response [200]>
        """
     
        # By using the 'with' statement we are sure the session is closed, thus we
        # avoid leaving sockets open which can trigger a ResourceWarning in some
        # cases, and look like a memory leak in others.
        with sessions.Session() as session:
            return session.request(method=method, url=url, **kwargs)

    更多详细资料

    更多requests模块相关的​文档见:http://cn.python-requests.org/zh_CN/latest/

















  • 相关阅读:
    git can't merge 的处理 代码冲突问题的解决
    react 父组件向子组件传递函数
    node fs 文件/目录 删除
    node 调用Python exec child_process 模块
    node 设置自动启用定时任务控件 node-schedule
    Python 安装
    常见Python 中pip用法(待继续添加)
    机器审核图片学习(2)安装pornDetector所用环境-python、scikit-learn、opencv
    机器审核图片学习(1)pornDetector
    机器学习工具
  • 原文地址:https://www.cnblogs.com/daliangtou/p/5483918.html
Copyright © 2011-2022 走看看