requests几个常用方法源码

  1. def request(method, url, **kwargs):
  2. """Constructs and sends a :class:`Request <Request>`.
  3. :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
  4. :param url: URL for the new :class:`Request` object.
  5. :param params: (optional) Dictionary, list of tuples or bytes to send
  6. in the query string for the :class:`Request`.
  7. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  8. object to send in the body of the :class:`Request`.
  9. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
  10. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
  11. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
  12. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
  13. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
  14. or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
  15. defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
  16. to add for the file.
  17. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
  18. :param timeout: (optional) How many seconds to wait for the server to send data
  19. before giving up, as a float, or a :ref:`(connect timeout, read
  20. timeout) <timeouts>` tuple.
  21. :type timeout: float or tuple
  22. :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
  23. :type allow_redirects: bool
  24. :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
  25. :param verify: (optional) Either a boolean, in which case it controls whether we verify
  26. the server's TLS certificate, or a string, in which case it must be a path
  27. to a CA bundle to use. Defaults to ``True``.
  28. :param stream: (optional) if ``False``, the response content will be immediately downloaded.
  29. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
  30. :return: :class:`Response <Response>` object
  31. :rtype: requests.Response
  32. Usage::
  33. >>> import requests
  34. >>> req = requests.request('GET', 'https://httpbin.org/get')
  35. >>> req
  36. <Response [200]>
  37. """
  38. # By using the 'with' statement we are sure the session is closed, thus we
  39. # avoid leaving sockets open which can trigger a ResourceWarning in some
  40. # cases, and look like a memory leak in others.
  41. with sessions.Session() as session:
  42. return session.request(method=method, url=url, **kwargs)
  43. def get(url, params=None, **kwargs):
  44. r"""Sends a GET request.
  45. :param url: URL for the new :class:`Request` object.
  46. :param params: (optional) Dictionary, list of tuples or bytes to send
  47. in the query string for the :class:`Request`.
  48. :param \*\*kwargs: Optional arguments that ``request`` takes.
  49. :return: :class:`Response <Response>` object
  50. :rtype: requests.Response
  51. """
  52. kwargs.setdefault('allow_redirects', True)
  53. return request('get', url, params=params, **kwargs)
  54. def options(url, **kwargs):
  55. r"""Sends an OPTIONS request.
  56. :param url: URL for the new :class:`Request` object.
  57. :param \*\*kwargs: Optional arguments that ``request`` takes.
  58. :return: :class:`Response <Response>` object
  59. :rtype: requests.Response
  60. """
  61. kwargs.setdefault('allow_redirects', True)
  62. return request('options', url, **kwargs)
  63. def head(url, **kwargs):
  64. r"""Sends a HEAD request.
  65. :param url: URL for the new :class:`Request` object.
  66. :param \*\*kwargs: Optional arguments that ``request`` takes. If
  67. `allow_redirects` is not provided, it will be set to `False` (as
  68. opposed to the default :meth:`request` behavior).
  69. :return: :class:`Response <Response>` object
  70. :rtype: requests.Response
  71. """
  72. kwargs.setdefault('allow_redirects', False)
  73. return request('head', url, **kwargs)
  74. def post(url, data=None, json=None, **kwargs):
  75. r"""Sends a POST request.
  76. :param url: URL for the new :class:`Request` object.
  77. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  78. object to send in the body of the :class:`Request`.
  79. :param json: (optional) json data to send in the body of the :class:`Request`.
  80. :param \*\*kwargs: Optional arguments that ``request`` takes.
  81. :return: :class:`Response <Response>` object
  82. :rtype: requests.Response
  83. """
  84. return request('post', url, data=data, json=json, **kwargs)
  85. def put(url, data=None, **kwargs):
  86. r"""Sends a PUT request.
  87. :param url: URL for the new :class:`Request` object.
  88. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  89. object to send in the body of the :class:`Request`.
  90. :param json: (optional) json data to send in the body of the :class:`Request`.
  91. :param \*\*kwargs: Optional arguments that ``request`` takes.
  92. :return: :class:`Response <Response>` object
  93. :rtype: requests.Response
  94. """
  95. return request('put', url, data=data, **kwargs)
  96. def patch(url, data=None, **kwargs):
  97. r"""Sends a PATCH request.
  98. :param url: URL for the new :class:`Request` object.
  99. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  100. object to send in the body of the :class:`Request`.
  101. :param json: (optional) json data to send in the body of the :class:`Request`.
  102. :param \*\*kwargs: Optional arguments that ``request`` takes.
  103. :return: :class:`Response <Response>` object
  104. :rtype: requests.Response
  105. """
  106. return request('patch', url, data=data, **kwargs)
  107. def delete(url, **kwargs):
  108. r"""Sends a DELETE request.
  109. :param url: URL for the new :class:`Request` object.
  110. :param \*\*kwargs: Optional arguments that ``request`` takes.
  111. :return: :class:`Response <Response>` object
  112. :rtype: requests.Response
  113. """
  114. return request('delete', url, **kwargs)

response

  1. # respone属性
  2. print(respone.text)
  3. print(respone.content)
  4. print(respone.status_code)
  5. print(respone.headers)
  6. print(respone.cookies)
  7. print(respone.cookies.get_dict())
  8. print(respone.cookies.items())
  9. print(respone.url)
  10. print(respone.history) 【】形式 重定向
  11. print(respone.encoding)
  12. #关闭:response.close()
  13. from contextlib import closing
  14. with closing(requests.get('xxx',stream=True)) as response:
  15. for line in response.iter_content():
  16. pass

编码问题

  1. res = requests.get(url=url, headers=headers)
  2. res.encoding='gbk' 第一种
  3. res.apparent_encoding 第二种
  1. res = requests.get(url=url, headers=headers)
  2. res.iter_content()
  3. 用于视频、图片等

解析json

  1. res = requests.get(url=url, headers=headers)
  2. res.json()

SSL证书(了解,基本不用)

  1. res = requests.get(url=url, headers=headers,verify=False) 不验证证书,报错返回200
  1. res = requests.get(url=url, headers=headers,cert={...}) 手动加上证书

代理(重点)

  1. res = requests.get(url=url, headers=headers,proxies={'http':'http://localhost:9743',})
  2. 协议+地址和端口号
  3. 代理池:列表里面放ip,随机取值
  4. 高匿代理:后端无法拿到IP
  5. 透明代理:后端可以拿到IP

超时

  1. res = requests.get(url=url, headers=headers,timeout=10)

认证设置(了解,基本不用)

  1. res = requests.get(url=url, headers=headers,auth=())

异常

  1. try:
  2. r=requests.get('http://www.baidu.com',timeout=0.00001)
  3. except ReadTimeout:
  4. print('===:')
  5. except ConnectionError: #网络不通
  6. print('-----')
  7. except Timeout:
  8. print('aaaaa')
  9. except RequestException:
  10. print('Error')

文件上传

  1. res = requests.post(url=url,files={} )