- Requests has get,post,put,delete,head,options.
Passing parameters for URLs
>>> Payload = {' key1 ': ' value1 ', ' Key2 ': ' value2 '} >>> R = requests. Get("Http://httpbin.org/get", params=payload)
< Span class= "GP" > < Span style= "FONT-SIZE:16PX;" >r.text Get response content < Span class= "GP" >
Span style= "FONT-SIZE:16PX;" >r.encoding decoding
r.content or binary response content
r.json () extract the JSON
in the return message < Span class= "GP" > r.status _code Get the response code
R.status_code==requests.codes.ok see if the Web site can open
R.raise_for_status () throws a 404 exception
R.headers view headers
r.cookies View Cookies
send cookies:
>>> url = Span class= "s" > ' http://httpbin.org/cookies ' >>> cookies = dict (cookies_are= ' working ' Span class= "P" >) >>> r = requestsget (urlcookies =cookies) >>> r text
< Span class= "p" > < Span class= "s" >
Custom headers:
>>>ImportJson>>>Url=' Https://api.github.com/some/endpoint '>>>payload = { ' some ' : ' data ' }>>> headers = Span class= "p" >{ ' Content-type ' : ' Application/json ' }>>> r = requestspost (urldata= json. Dumps (payloadheaders= headers)
< Span class= "p" > < Span class= "s" >requests is auto-redirected, To track redirects, use R.url,r.history to see if they are redirected
>>> r = requests. Get ( ' http://github.com ' ) >>> r. Url ' https://github.com/' >>> r. Status_code200>>> r. History[<response [301]>]
< Span class= "p" > < Span class= "P" >
allow_redirects parameter disable redirection processing
Requests. Get(' http://github.com 'allow_redirects=False)R. Status_code301R. History[]
timeoutparameter is set to stop waiting for a response after a number of seconds
Errors and exceptions
Requests throws an exception when a network problem is encountered, such as a DNS query failure, a denial of connection, and so on ConnectionError .
When a rare invalid HTTP response is encountered, requests throws an HTTPError exception.
If the request times out, an Timeout exception is thrown.
If the request exceeds the set maximum number of redirects, an exception is thrown TooManyRedirects .
All exceptions that are explicitly thrown by requests inherit from requests.exceptions.RequestException .
Requests simple to use