1 - About Python request module
Requests is a python module allowing to use the http protocol in a very simple way! You will discover its power when you want to recover data from a web page at work through a proxy. Because indeed, it really manages everything! Proxies, cookies, ssl, multipart uploads and many other cool things! We offer in this tutorial, some examples of uses of this library.
2 - Installation
As with all python modules, W advise you to use the pip utility:
pip install requests
3 - Create a request
First, let's import the Requests module:
import requests
Now let's try to retrieve the page from https://en.wikipedia.org/ and display it using the requests module
code
# importing the requests module
import requests
url = "https://en.wikipedia.org/"
# get the content of the wikipedia website
r = requests.get (url)
# display the content of the page
print (r.text)
4 - The methods associated with the requests object
r = requests.get(url)
r = requests.post(url)
r = requests.put(url)
r = requests.delete(url)
r = requests.head(url)
r = requests.patch(url)
r = requests.options(url)
- get : method used to retrieve information from the given server using a given url.
- post : requests that a web server accepts the data enclosed in the body of the request message.
- put : method requests that the enclosed entity be stored under the supplied url.
- delete : method to deletes the specified resource
- head : method to asks for a response identical to that of a get request, but without the response body.
- patch : method used for modify capabilities. The patch request only needs to contain the changes to the resource, not the complete resource.
5 - Read the response
To read the response we have already seen r.text above. For the rest, it's always that simple, here is the method:
r.text #Returns content to unicode
r.content #Returns content in bytes
r.json #Returns the content in json form
r.headers #Returns the headers as a dictionary
r.status_code #Return status code
Younes Derfoufi
my-courses.net
my-courses.net