Python

Request 모듈 사용법

Always-Try 2021. 1. 26. 17:48

써니나타스의 웹 해킹 문제를 풀던 도중 해당 모듈에 대한 필요성을 느껴서 정리한다.

Requests 모듈은 파이썬에서 HTTP 요청을 전송하기 위해 사용된다. 

 

HTTP 요청은 GET, POST 2가지 방식이 있으며, 2가지 방법에 따라 문법이 조금씩 다르다.

GET은 파라미터를 params 로 보내고, POST는 data로 보내는 차이점이 있다.

 

1. GET 요청

import requests
URL = 'http://www.tistory.com'   #요청을 보낼 URL
param = {'ID':'admin'}         #GET 요청에 대한 파라미터
response = requests.get(URL, params=params)

print(response)
print(response.url)
print(response.status_code)
print(response.headers)
print(response.text)

#요청 구문에 특별한 값을 추가하려면 아래와 같이하면 된다.
header = {'Content-Type':'text/html'}
cookies = {'Session_ID': 'test'}
response = requests.get(URL, headers=header)
response = requests.get(URL, cookies=cookies)

 

 

2. POST 요청

import requests

URL = 'http://www.tistory.com'   #요청을 보낼 URL
data = {'parameter1':'value1', 'parameter2':'value2'} #POST 요청에 대한 파라미터. #좀 더 depth 있는 파라미터를 넣으려면 json 모듈 필요

response = requests.post(URL, data=data)