티스토리 뷰

728x90
반응형

우선 requests 모듈이 설치가 되어 있지 않다면 별도로 설치를 해주어야 합니다. 

pip install requests

그리고 requests 모듈을 사용해서 구글 페이지를 요청해보고, 잘 요청되었다면 받아온 응답을 html 파일로 저장해보겠습니다.

import requests
res = requests.get("http://google.com")
res.raise_for_status() # 응답코드 200(정상)이 아니면 예외처리 및 프로그램 종료
print(len(res.text))
with open("google.html", "w", encoding="utf8") as f:
	f.write(res.text)

위 코드를 잠깐 설명하자면, requests.get 함수를 사용해서 google.com 페이지를 요청하고, 그 결과 내용물을 res 변수에 담습니다. res 변수에 담긴 것은 단순 문자열이 아닌 requests 모듈에서 정의한 Response 객체(클래스) 형태로 반환이 됩니다.

 

Response 클래스에는 raise_for_status() 함수가 있습니다. 그 외에도 다양한 함수들이 정의되어 있는데 아래 문서를 참고하면 될 것 같습니다.

https://docs.python-requests.org/en/latest/api/#requests.Response.raise_for_status

 

Developer Interface — Requests 2.26.0 documentation

Developer Interface This part of the documentation covers all the interfaces of Requests. For parts where Requests depends on external libraries, we document the most important right here and provide links to the canonical documentation. Main Interface All

docs.python-requests.org

raise_for_status() 함수는 만약 HTTPError 에 관련된 예외가 발생했을 경우 프로그램을 종료시키는 함수입니다. 보통 일반적으로 HTTPError라고 하면 상태코드 400 번 이상을 의미합니다. 예를 들어 잘못된 페이지거나 서버가 다운된 페이지거나 URL주소가 잘못되었거나 등등이 될 수 있겠습니다.

 

다시 코드로 돌아가서, 만약 요청 페이지에 오류가 없어서 정상적으로 응답코드 200이 반환되었다면, res.text 즉 Rseponse 클래스의 text 속성의 길이를 출력하라고 되어 있습니다.

 

여기서 Response 클래스의 text 속성은 단순히 반환된 응답 페이지의 내용물을 유니코드 인코딩 형식으로 반환한 것을 의미합니다. https://docs.python-requests.org/en/latest/api/#requests.Response.text

 

Developer Interface — Requests 2.26.0 documentation

Developer Interface This part of the documentation covers all the interfaces of Requests. For parts where Requests depends on external libraries, we document the most important right here and provide links to the canonical documentation. Main Interface All

docs.python-requests.org

그리고 마지막으로 Python의 내장함수인 open 함수를 통해 google.html 이란 파일을 만들고, 응답 페이지로부터 받아온 내용물을 파일 쓰기 합니다. 그리고 그 결과로 아래와 같은 파일이 만들어집니다.

위 파일을 열면 아래와 같이 나옵니다.

실제 구글 사이트와 비교해보면 거의 유사합니다. 단지 스타일이나 이미지 같은 것들은 상대경로 그대로 가져와서 현재 제 컴퓨터에 이미지 파일이나 CSS나 JS 파일들이 존재하지 않아서 위와 같이 깨져서 보이는 것일 뿐입니다.

 

아무튼 Python의 requests 모듈을 통해서 가져오길 원하는 페이지를 잘 가져와서 파일로 저장한 것을 확인해보았습니다.

 

- 끝 -

728x90
반응형
댓글