[python] Requests 라이브러리 사용법

평소 크롤링에 관심이 있어 파이썬에 기웃거리다가 알게된 내용을 정리해봅니다.Requests 라이브러리는 해당 주소로 요청을 보내면 응답을 받도록 해주는 HTTP 클라이언트 입니다.

1.설치 및 모듈로드

#pip를 이용한 모듈설치
pip install requests
 
#requests 모듈 로드
>>>import requests

 

2.사용방법

*요청보내기

HTTP method GET, POST, PUT, DELETE, OPTION을 요청할 수 있습니다.

>>> r = requests.get('https://api.github.com/events', param = {'key':'value'})
>>> r = requests.post('https://httpbin.org/post', data = {'key':'value'})
>>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})
>>> r = requests.delete('https://httpbin.org/delete')
>>> r = requests.head('https://httpbin.org/get')
>>> r = requests.options('https://httpbin.org/get')

 

* 복잡한 요청

튜플이나, 딕셔너리 형태로 데이터를 전송해야하는 경우가 있을 수 있습니다.
아래의 코드중에 ‘payload_tuple’ 변수를 post로 전송한 뒤 r1.text을 확인해 보면 형태가 변경 되어 응답 된 것을 확인 할 수 있습니다.

>>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
>>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
>>> payload_dict = {'key1': ['value1', 'value2']}
>>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)
>>> print(r1.text)
{
  ...
  "form": { 
    "key1": [
      "value1",
      "value2"
    ]
  },
  ...
}
>>> r1.text == r2.text
True

이러한 형태의 변환 없이 요청을 보내려면 json형식으로 변환하여 보내면 되겠습니다.
보내는 방법은 데이터 자체를 json으로 인코딩 해서 보내는방법과 v2.4.2버전 부터 에 추가된 json 파라메터를 이용하는 방법입니다.

– json으로 인코딩하기

>>> import json
 
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'} 
>>> r = requests.post(url, data=json.dumps(payload))

-json파라메터 이용하기

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
 >>> r = requests.post(url, json=payload)

*파일보내기

>>> url = 'https://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
 
>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

 

*응답컨텐츠

응답은 requests.text 또는 requests.content로 확인 할 수 있습니다. 이 방법의 차이는 전자는 텍스트 형식이고 후자는 바이트형식입니다.
또한 requests.encoding으로 인코딩을 확인 할 수 있으며 인코딩 변환은 requests.encoding = ‘utf-8’ 같이 원하는 형식을 지정해주면 됩니다.
>>> import requests
 
>>> r = requests.get('https://api.github.com/events')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
...
...
...'
 
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

 

*응답상태코드

응답에 서공하면 상태코드 200을 리턴합니다.
(400번대 코드를 리턴하면 클라이언트 에러, 500번대를 이런하면 서버측 에러입니다.)
>>> r = requests.get('https://httpbin.org/get')
>>> r.status_code
200
>>> r.status_code == requests.codes.ok
True
 
>>> bad_r = requests.get('https://httpbin.org/status/404')
>>> bad_r.status_code
404
 
>>> bad_r.raise_for_status()
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error

만약 status_code가 200이면 raise_for_status()를 사용하면 빈값을 리턴합니다.

*헤더변경

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)

 

*헤더응답

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}
 
>>> r.headers['Content-Type']
'application/json'
 
>>> r.headers.get('content-type')
'application/json'

 

* 쿠키

만약 응답에 쿠키가 포함 되어있다면 아래와 같이 접근할 수 있습니다.

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
 
>>> r.cookies['example_cookie_name']
'example_cookie_value'


출처: https://yoojisung.tistory.com/13 [개발자 유지성의 블로그]

반대로 서버에게 쿠키를 보내야할 경우 cookies 파라메터를 이용합니다.

>>> url = 'https://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
 
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

 

*리다이렉션 과 히스토리

경우에 따라서 해당페이지에서 리다이렉션이 되는 것을 방지하고자 할때 allow_redirects 매개변수를 사용합니다.

>>> r = requests.get('http://github.com/', allow_redirects=False)
 
>>> r.status_code
301
 
>>> r.history
[]
 
>>> r = requests.head('http://github.com/', allow_redirects=True)
 
>>> r.url
'https://github.com/'
 
>>> r.history
[<Response [301]>]

 

*타임아웃

timeout 매개변수를 사용해서 설정한 시간이 지나면 응답을 종료합니다. 응답이 돌아올때까지 서버가 일을 하는 것을 방지 하는 목적같습니다.

>>> requests.get('https://github.com/', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

requests 공식 사이트

http://docs.python-requests.org/en/master/


Warning: Attempt to read property "comment_ID" on null in /var/www/html/blog/wp-includes/comment-template.php on line 677

Warning: Attempt to read property "user_id" on null in /var/www/html/blog/wp-includes/comment-template.php on line 28

Warning: Attempt to read property "comment_ID" on null in /var/www/html/blog/wp-includes/comment-template.php on line 48
익명에 답글 남기기 응답 취소

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다