Python HTTP Clients: Requests 라이브러리

dpwl·2024년 7월 13일

Data Analysis with Python

목록 보기
47/48

1. Python HTTP Clients

Python HTTP Clients는 Python에서 웹 서버와 HTTP/HTTPS 프로토콜을 사용하여 데이터 송수신을 수행하는 도구이다. 이는 웹 스크래핑, API 호출, 웹 서비스 통신 등 다양한 용도로 활용된다.

종류:
1) requests:

  • 사용하기 쉽고 다양한 HTTP 메서드를 지원한다.
  • 복잡한 HTTP 작업도 간편하게 처리할 수 있다.
  • 가장 널리 사용되는 HTTP 클라이언트 라이브러리다.

2) urllib:

  • Python 표준 라이브러리에 포함된 모듈로, HTTP 요청을 보내는 기본적인 기능을 제공한다.
  • requests보다 API가 조금 더 복잡하고 여러 모듈로 나뉘어져 있다.

3) http.client:

  • Python 표준 라이브러리에 포함된 낮은 수준의 HTTP 클라이언트 모듈이다.
  • 매우 높은 수준의 커스터마이징이 가능하지만, 사용하기 복잡하다.

2. Requests 라이브러리

Requests는 가장 많이 사용되는 Python HTTP 라이브러리로, 간단하고 직관적인 인터페이스를 제공한다.

2.1 requests.request 기능

requests.request(method, url, **kwargs)
# 주어진 HTTP 메서드로 요청을 보낸다.
  • method: HTTP 메서드 (GET, POST, PUT, DELETE 등)
  • url: 요청할 URL
  • kwargs: 기타 추가적인 매개변수

예시:

import requests
req = requests.request('GET', 'https://httpbin.org/get')
print(req.status_code)  # HTTP 응답 상태 코드 출력

2.2 requests.get 기능

requests.get(url, params=None, **kwargs)
# GET 메서드를 사용하여 요청을 보낸다.
  • url: 요청할 URL
  • params: URL에 추가할 쿼리 매개변수
  • kwargs: 기타 추가적인 매개변수
import requests
url = 'https://httpbin.org/get'
response = requests.get(url)
print(response.text)  # 응답 내용 출력

2.3 Response 속성

  • content: 바이트 형식의 응답 내용
  • text: 유니코드 형식의 응답 내용
  • status_code: HTTP 응답 상태 코드 (200, 404 등)
  • reason: HTTP 응답 상태에 대한 설명 (예: "OK", "Not Found")

2.4 Requests 사용하기

1) 설치

pip install requests

2) import

import requests

3) HTTP 요청 보내고 응답 받기

url = "https://[github-username].github.io/[repository-name]/"
response = requests.get(url)
print(response)

# response = requests.request('GET', url)
print(type(response))

# <class 'requests.models.Response'>
print('status code:', response.status_code)

# status code: 200
print('content:', response.content)

# content: b'<!DOCTYPE html>\n<html lang="ko">\n  <head>\n    <meta charset="UTF-8" />\n    <title>\xea\xb9\x80\xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0\xec\x9d\x98 \xec\x9d\xb4\xeb\xa0\xa5\xec\x84\x9c</title>\n    <link rel="stylesheet" href="style.css" />\n  </head>\n  <body>\n    <header id="main-header">\n      <h1 id="name">\xea\xb9\x80\xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0</h1>\n
print('content type:', type(response.content))

# content type: <class 'bytes'>
print('text:', response.text)

# text: <!DOCTYPE html>
# <html lang="ko">
#   <head>
#     <meta charset="UTF-8" />
#     <title>홍길동의 이력서</title>
#     <link rel="stylesheet" href="style.css" />
#   </head>
#   <body>
#     <header id="main-header">
#       <h1 id="name">홍길동</h1>
#       <p id="introduction">
#         데이터를 통해 비즈니스 문제를 해결하고 가치를 창출하는 경험이 풍부한
#         데이터 분석가입니다.
#       </p>
#     </header>
#     <main id="main-content">
#       <section class="main-section contact-section">
#         <h2>Contact</h2>
#         <p id="mobile"><b>Mobile:</b> 010-1234-5678</p>
#         <p id="email"><b>E-mail:</b> kimdata@example.com</p>
#         <p id="address"><b>Address:</b> 서울시 강남구</p>
#         <p><b>Socials & Websites:</b></p>
# ...
#   </body>
# </html>
print('text type:', type(response.text))

# text type: <class 'str'>
profile
거북선통통통통

0개의 댓글