Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python requests 모듈로 배우는 GET·POST 요청 완벽 가이드

Python은 웹페이지에 접속하는 것은 물론, 웹페이지로 데이터를 전송하는 작업까지 손쉽게 처리할 수 있습니다. httplib, urllib, httplib2 등 다양한 모듈이 존재하지만, 그중에서도 requests 모듈이 가장 간결하고 직관적입니다. 이 모듈을 사용하면 GET과 POST 방식을 활용하는 프로그램을 짧고 강력하게 작성할 수 있습니다.

GET 메서드란?

GET 메서드는 Python requests 모듈에서 제공하는 기능으로, 지정된 URL에서 데이터를 가져오는 데 사용됩니다. 아래 예제에서는 실제 웹사이트에 요청을 보낸 후, get 메서드를 통해 문자 인코딩 방식, HTTP 응답 코드, 응답 소요 시간, 헤더 정보 그리고 페이지 본문의 일부를 확인해 보겠습니다.

예제

import requests

req = requests.get('https://www.tutorialspoint.com/')

# 페이지 인코딩
e = req.encoding
print("Encoding: ",e)

# 응답 코드
s = req.status_code
print("Response code: ",s)

# 응답 시간
t = req.elapsed
print("Response Time: ",t)


t = req.headers['Content-Type']
print("Header: ",t)

z = req.text
print("\nSome text from the web page:\n",z[0:200])

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Encoding: UTF-8
Response code: 200
Response Time: 0:00:00.103850
Header: text/html; charset=UTF-8

Some text from the web page:<!--<html lang="en-US"> <!--<![endif]-->
<!--<head>
Bas -->

POST 메서드란?

POST 메서드는 주로 폼(form)을 통해 서버로 데이터를 전송하여, 서버에 새로운 데이터를 생성하거나 기존 데이터를 갱신할 때 사용됩니다. requests 모듈의 post 메서드는 URL과 data 매개변수 값만 넘겨주면 되기 때문에 데이터 전송 작업을 매우 간단하게 처리할 수 있습니다.

아래 예제에서는 httpbin.org 사이트에 post 메서드로 데이터를 전송한 뒤, 전송된 데이터가 어떤 형태로 처리되었는지 응답 결과를 통해 확인해 보겠습니다.

예제

import requests
in_values = {'username':'Jack','password':'Hello'}
res = requests.post('https://httpbin.org/post',data = in_values)
print(res.text)

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

{
"args": {},
"data": "",
"files": {},
"form": {
"password": "Hello",
"username": "Jack"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "28",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5ef75488-969f97a68bb72642b97b6d50"
},
"json": null,
"origin": "122.xxx.yy.zzz",
"url": "https://httpbin.org/post"
}