HTTP requests

pip install requests

GET Request

import requests

r =requests.get('https://xkcd.com/1906/')

Status Code

r.status_code

Headers

r.headers

r.headers['Content-Type']

Response Content

r.text

HTML parser

'\r\n<!DOCTYPE html>\r\n<html>\r\n<head>\r\n\r\n<link href="http://www.smbc-comics.com/comiccontrol/defaultstyles.css?=2" rel="stylesheet" type="text/css" />\r\n<link rel="shortcut icon"
href="http://www.smbc-comics.com/favicon.ico" type="image/x-icon" />\r\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\r\n<link rel="shortcut icon"
href="http://www.smbc-comics.com/favicon.ico" type="image/x-icon">\r\n<link rel="icon"
href="http://www.smbc-comics.com/favicon.ico"

Downloading and Saving an Image

import requests

receive = requests.get('https://imgs.xkcd.com/comics/making_progress.png')
with open(r'C:\Users\Dell\Desktop\comics\image5.png','wb') as f:
    f.write(recieve.content)

Passing Argument in the Request

import requests
ploads = {'things':2,'total':25}
r = requests.get('https://httpbin.org/get',params=ploads)
print(r.text)
print(r.url)
print(r.url)

POST Request

import requests
pload = {'username':'Olivia','password':'123'}
r = requests.post('https://httpbin.org/post',data = pload)
print(r.text)

JSON Response

Converting JSON to Python Dictionary

import requests
pload = {'username':'olivia','password':'123'}
r = requests.post('https://httpbin.org/post',data = pload)

print(r.json())

Converting JSON to Python dictionary and storing in a variable.

import requests
pload = {'username':'olivia','password':'123'}
r = requests.post('https://httpbin.org/post',data = pload)
r_dictionary= r.json()
print(r_dictionary['form'])

Reference : https://www.datacamp.com/community/tutorials/making-http-requests-in-python

Last updated