IT/Python

[Python] Reqeust 모듈 사용 법

반응형

Get요청

일반적으로 GET요청은 host/path?pram1=value1&pram2=value2... 형식으로 되있습니다.

requests는 매개변수 전달을 하는 방법은 아래와 같습니다.

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://host/path', params=payload)
  • 예시
import requests

host = 'https://search.naver.com'
path = '/search.naver'
params = {'query':'kimdragon'}

url = host + path
response = requests.get(url,params=params)

Post요청

POST 방식은 대부분 클라이언트에서 데이터를 전송하며 데이터는 단순 객체 또는 파일이 될 수 있습니다.

  • 단순 객체
data = {'key':'value'}
r = requests.post('https://host/path', data = data )
  • 파일
url = 'https://host/path'
files = {'file': open('text.xls', 'rb')}
r = requests.post(url, files=files)
  • dict데이터

dict형 데이터는 json을 변환해야합니다.

import json
url = 'https://host/path'
payload = {'key': 'value'}
r = requests.post(url, data=json.dumps(payload))

요청에 대한 응답(response) 데이터 속성

print(response.status_code) #응답 상태 코드
print(response.url) #요청했던 url
print(response.text) #응답데이터(str) - 주로 웹 페이지 소스코드나 문자 데이터 or json을 확인할 때
print(response.content) #응답데이터(byte) - 주로 음악, 비디오등 byte 자체를 받아 저장시킬 때 사용
print(response.encoding) #응답데이터의 인코딩 방식
print(response.headers) #응답데이터의 헤더
  • 응답데이터가 json일 경우

json.dump 함수를 쓰지 않아도 아래와 같이 반환 가능

data = response.json()

CURL 주요 옵션 설명

-d : data 함께 전달할 파라미터값 설정하기
-f : files
-j : jsons
-H : hedears
-A : 헤더의 user-agent가 안내
-X : 요청시 필요한 메소드 방식 안내
-G : 전송할 사이트 url 및 ip 주소
-i : 사이트의 Header 정보만 가져오기
-I : 사이트의 Header와 바디 정보를 함께 가져오기
-u : 사용자 정보
-x : 프록시

CURL 옵션을 request 모듈에 적용하기

curl -x https://proxy.com -X POST -H "Content-Type: Application/json" -d "{\"key\": \"value\"}" https://host/path
import json

url = 'https://host/path'
payload = {'key': 'value'}
headers = {'Content-Type': 'Application/json'}
proxies = {'http': 'http://proxy.com', 'https': 'https://proxy.com'}

r = requests.post(url, data=json.dumps(payload), headers=headers, proxies=proxies )
반응형