笔记-python-lib-requests常用类/方法/属性

时间:2023-03-10 01:49:57
笔记-python-lib-requests常用类/方法/属性

笔记-python-lib-requests常用类/方法/属性

1.      requests模块常用类/方法/属性

在使用中发现对requests模块不够熟悉,写了几个案例后重新整理了一下文档,罗列出常使用的类/方法/属性。

详细情况请查看:http://docs.python-requests.org/en/master/

1.1.    class requests.request()

requests.request(method, url, **kwargs)

Constructs and sends a Request.

Returns: Response object

Return type: requests.Response

  1. requests.get(url, params=None, **kwargs)

Sends a GET request.

Parameters:

url – URL for the new Request object.

params – (optional) Dictionary, list of tuples or bytes to send in the body of the Request.

**kwargs – Optional arguments that request takes.

Returns:  Response object

Return type:requests.Response

  1. requests.post(url, data=None, json=None, **kwargs)[source]

Sends a POST request.

1.2.    Request Sessions

最常用的功能类。

class requests.Session

A Requests session.Provides cookie persistence, connection-pooling, and configuration.

常用方法/属性:

  1. auth = None

Default Authentication tuple or object to attach to Request.

  1. cert = None

SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

  1. close()[source]

Closes all adapters and as such the session

  1. cookies = None

A CookieJar containing all currently outstanding cookies set on this session. By default it is a RequestsCookieJar, but may be any other cookielib.CookieJarcompatible object.

  1. delete(url, **kwargs)[source]

Sends a DELETE request. Returns Response object.

  1. get(url, **kwargs)[source]

Sends a GET request. Returns Response object.

  1. head(url, **kwargs)[source]

Sends a HEAD request. Returns Response object.

  1. headers = None

A case-insensitive dictionary of headers to be sent on each Request sent from this Session.

  1. post(url, data=None, json=None, **kwargs)[source]

Sends a POST request. Returns Response object.

  1. prepare_request(request)[source]

Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of theSession.

  1. proxies = None

Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each Request.

1.3.    class requests.Response

class requests.Response

The Response object, which contains a server’s response to an HTTP request.

表示HTTP请求返回内容的类。查看返回信息。

  1. apparent_encoding

The apparent encoding, provided by the chardet library.

  1. close()[source]

Releases the connection back to the pool. Once this method has been called the underlying raw object must not be accessed again.

Note: Should not normally need to be called explicitly.

  1. content:Content of the response, in bytes.
  2. cookies = None

A CookieJar of Cookies the server sent back.

  1. elapsed = None

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.

  1. encoding = None

Encoding to decode with when accessing r.text.

  1. headers = None

Case-insensitive Dictionary of Response Headers. For example, headers['content-encoding'] will return the value of a 'Content-Encoding'response header.

  1. history = None

A list of Response objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request.

  1. is_permanent_redirect

True if this Response one of the permanent versions of redirect.

  1. is_redirect

True if this Response is a well-formed HTTP redirect that could have been processed automatically (by Session.resolve_redirects).

  1. links:Returns the parsed header links of the response, if any.
  2. next:Returns a PreparedRequest for the next request in a redirect chain, if there is one.
  3. ok:Returns True if status_code is less than 400, False if not.

This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK.

  1. raise_for_status()[source]:Raises stored HTTPError, if one occurred.
  2. reason = None

Textual reason of responded HTTP Status, e.g. “Not Found” or “OK”.

  1. request = None

The PreparedRequest object to which this is a response.

  1. status_code = None

Integer Code of responded HTTP Status, e.g. 404 or 200.

  1. text

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

  1. url = None

Final URL location of Response.

1.4.    RequestCookieJar

class requests.cookies.RequestsCookieJar(policy=None)

Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.

需要查看cookie信息时使用。

  1. get_dict(domain=None, path=None)

Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements.

  1. items()

Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call dict(RequestsCookieJar) and get a vanilla python dict of key value pairs.