Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python 프로그래밍을 사용한 GET 및 POST 요청

<시간/>

Python을 사용하여 웹 페이지에 액세스하고 웹 페이지에 콘텐츠를 게시할 수 있습니다. httplib, urllib, httplib2 등과 같은 다양한 모듈이 있지만 requests 모듈이 가장 간단하고 GET 및 POST 메서드를 포함하는 간단하면서도 강력한 프로그램을 작성하는 데 사용할 수 있습니다.

GET 메소드

GET 메소드는 웹 URL에서 데이터를 가져오는 데 사용되는 python 요청 모듈의 일부입니다. 아래의 예에서 우리는 우리 자신의 웹사이트에 접근하여 get 메소드를 통해 다양한 응답을 찾습니다. 인코딩, 응답 시간, 헤더 및 본문 일부를 얻습니다.

예시

import requests

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

# Page encoding
e = req.encoding
print("Encoding: ",e)

# Response code
s = req.status_code
print("Response code: ",s)

# Response Time
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:

POST 방식

POST 방법은 서버에서 데이터를 생성하거나 업데이트하기 위해 주로 양식을 통해 서버로 데이터를 보내는 데 사용됩니다. 요청 모듈은 데이터 매개변수의 URL과 값을 취하여 데이터를 직접 보낼 수 있는 post 메소드를 제공합니다.

아래 예에서는 post 메소드를 통해 httpbin.org 웹사이트에 일부 데이터를 게시하고 게시 방식에 대한 응답을 받습니다.

예시

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"
}