[2주차 - Day1] HTTP 요청 주고받기 - Requests

2023. 3. 20. 15:28BOOTCAMP/프로그래머스 인공지능 데브코스

웹 브라우저는 HTML 요청을 보내고, HTTP 응답에 담긴 HTML 문서를 우리가 보기 쉬운 형태로 화면을 그려주는 역할을 담당합니다.

웹 페이지는 HTML이라는 형식으로 되어있고, 웹 브라우저는 우리가 HTTP 요청을 보내고, 응답받은 HTML 코드를 렌더링 해줍니다.

 

<! DOCTYPE html>를 통해 HTML5 임을 명시합니다.

<!DOCTYPE html>
<html>
    <head>
        <title>Example Document</title>
    </head>
    <body>
    	<h1>Hello World!</h1>
        <p>My name is Mussg!</p>
    </body>
</html>

<html>로 열고, </html>로 닫으며, Head로 문서에 대한 정보(제목, 언어 등)를 작성합니다.

<tag>
  Contents 1
  Contents 2
  ...
</tag>

HTML은 여러 태그(Tag)로 감싼 요소(Element)의 집합으로 이루어져 있습니다.

태그로 내용을 묶어 글의 형식을 지정합니다.

<p>이것은 글씨입니다.</p>
<p><strong>진한 글씨는 이렇게 씁니다.</strong></p>

<strong>으로 진한 글씨를 씁니다.

<h1>1번째 소제목은 이렇게 달 수 있죠</h1>
<h2>2번째 소제목은 이렇게 달 수 있죠</h2>
<h3>3번째 소제목은 이렇게 달 수 있죠</h3>

소제목은 <h1>, <h2> 등으로 달 수 있으며, 태그는 그에 맞는 속성(attribute)를 가지기도 합니다.

따라서 웹 스크래핑 관점으로 볼 때, 어떤 태그에 찾고자하는 내용이 묶여있는지 파악하는 것이 중요합니다.

 

# requests 라이브러리

%pip install requests

Requirement already satisfied: requests in ./opt/anaconda3/lib/python3.9/site-packages (2.28.1)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in ./opt/anaconda3/lib/python3.9/site-packages (from requests) (1.26.11)
Requirement already satisfied: charset-normalizer<3,>=2 in ./opt/anaconda3/lib/python3.9/site-packages (from requests) (2.0.4)
Requirement already satisfied: certifi>=2017.4.17 in ./opt/anaconda3/lib/python3.9/site-packages (from requests) (2022.9.24)
Requirement already satisfied: idna<4,>=2.5 in ./opt/anaconda3/lib/python3.9/site-packages (from requests) (3.3)
Note: you may need to restart the kernel to use updated packages.

# requests 라이브러리를 불러온 후, NAVER의 홈 페이지를 요청한 후 응답 받아보기
import requests
res = requests.get("https://www.naver.com/robots.txt")
res # HTTP 응답이 담겨있음.

<Response [200]>

# Header를 확인해봅시다: .headers
res.headers

{'Server': 'NWS', 'Date': 'Mon, 20 Mar 2023 05:48:23 GMT', 'Content-Type': 'application/octet-stream', 'Content-Length': '38', 'Connection': 'keep-alive', 'Last-Modified': 'Thu, 02 Mar 2023 08:39:13 GMT', 'ETag': '"640060b1-26"', 'Vary': 'Accept-Encoding,User-Agent', 'Accept-Ranges': 'bytes', 'Strict-Transport-Security': 'max-age=63072000; includeSubdomains', 'Referrer-Policy': 'unsafe-url'}

# Body를 텍스트 형태로 확인해봅시다: .text
res.text[:1000]

'User-agent: *\nDisallow: /\nAllow : /$ \n'

웹 크롤링 

크롤러(Crawler)를 이용해서 웹 페이지의 정보를 인덱싱 - 데이터 색인

(e.g. 검색 엔진의 웹 크롤러)

 

웹 스크래핑

추출이 핵심 키워드로 웹 페이지로부터 우리가 원하는 정보를 추출하는 것 - 데이터 추출

(e.g. 날씨 데이터 가져오기, 주식 데이터 가져오기)

 

올바르게 HTTP 요청하기

웹 스크래핑/크롤링을 통해 어떤 목적을 달성하고자 하는지, 나의 웹 스크래핑/크롤링이 서버에 영향을 미치진 않는지 알아야 합니다.

# HTTP Method: POST (정보 갱신)
# POST를 활용하기 위해 다음 사이트를 이용해보도록 하겠습니다: https://webhook.site

# payload와 함께 POST를 보내봅시다: requests.post()
payload = {'name': "hello", 'age': 13}
res = requests.post("https://webhook.site/474e6824-31f8-46d5-8b89-d8d3d35c17f2", payload)

# 상태 코드(status code)를 확인해봅시다: .status_code
res.status_code

200
User-agent: *
Disallow: /

로봇 배제 프로토콜(REP): 로봇을 배제하는 약속으로, 이때 사용하는 것이 robots.txt으로 모든 user-agent에 대해서 접근 거부를 의미합니다. 

# robots.txt 가져오기

# requests 모듈을 불러온 후, 다음 웹사이트에 대한 robots.txt 정책을 확인해봅시다.
# https://www.naver.com

import requests
res = requests.get("https://www.naver.com/robots.txt")

print(res.text)

User-agent: *
Disallow: /
Allow : /$