[4/3] TIL - BeautifulSoup, 동적 웹사이트

Sangwon Jwa·2024년 4월 3일

데브코스 TIL

목록 보기
8/54
post-thumbnail

📖 학습 주제


  1. HTML을 분석해주는 BeautifulSoup
  2. 동적 웹사이트

✏️ 주요 메모 사항 소개


BeautifulSoup 라이브러리

  • requests 모듈을 이용하여 HTTP 요청을 보내고 응답을 받아 여러 요소를 살펴볼 수 있는데 응답의 내용이 아주 긴 텍스트로 오기 때문에 분석하기 어렵다는 문제점이 있다.
  • BeautifulSoup4 라이브러리를 이용한다면 HTML Parser를 사용해 HTML 코드를 우리가 원하는 요소만 가져올 수 있다.

실습

BeautifulSoup 설치

pip install bs4

BeautifulSoup 객체 만들기

import requests
from bs4 import BeautifulSoup

res = requests.get("https://www.example.com")
soup = BeautifulSoup(res.text, "html.parser")

print(soup.prettify())

실행결과

<!DOCTYPE html>
<html>
 <head>
  <title>
   Example Domain
  </title>
  <meta charset="utf-8"/>
  <meta content="text/html; charset=utf-8" http-equiv="Content-type"/>
  <meta content="width=device-width, initial-scale=1" name="viewport"/>
  <style type="text/css">
   body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
...
  </div>
 </body>
</html>

특정 요소 추출

soup.title  # title 태그를 추출
soup.head   # head 태그를 추출
soup.find("h1") # <h1> 태그로 감싸진 요소 하나 찾기
soup.find_all("h1") # <h1> 태그로 감싸진 요소들 찾기
soup.find("h1").name # 태그 이름 가져오기
soup.find("h1").text # 태그 내용 가져오기

원하는 요소 추출하기

  • URL에서 h3 태그로 이루어진 요소들을 찾은뒤 그 안에 a태그로 감싸진 부분에서title을 추출
import requests
from bs4 import BeautifulSoup

res = requests.get("http://books.toscrape.com/catalogue/category/books/travel_2/index.html")
soup = BeautifulSoup(res.text,"html.parser")
h3_results = soup.find_all("h3")

for book in h3_results:              #
	print(book.a["title"])

id class 로 원하는 요소 찾기

import requests
from bs4 import BeautifulSoup

res = requests.get("http://example.python-scraping.com/")
soup = BeautifulSoup(res.text, "html.parser")

soup.find("div", id="results")    				 #id 가 results인 div 태그를 찾기
find_result = soup.find("div", "page-header")    # class가 "page-header"인 div 태그를 찾기

find_result.h1.text.strip()                      # text 값 깔끔하게 가져오기

여러 겹의 태그로 이루어진 요소 찾기

user_agent = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}

import requests
from bs4 import BeautifulSoup

res = requests.get("https://hashcode.co.kr/", user_agent)
soup = BeautifulSoup(res.text, "html.parser")

# li 태그를 가지고 class 가 question-item-list인 요소들을 추출
questions = soup.find_all("li", "question-list-item")

# 추출한 요소들 중 question 클래스의 div태그 중 top 클래스의 div 태그의 h4 태그의 text를 추출
for question in questions:
    print(question.find("div","question").find("div", "top").h4.text)

동적 웹페이지

  • 정적(static) 웹 사이트 : HTML 내용이 고정됨. 같은 요청을 받으면 같은 응답을 받음, HTML 문서가 완전하게 응담.
  • 동적(dynamic) 웹 사이트 : HTML 내용이 변함. 새로고침을 할 때마다 새로운 웹 페이지를 불러오는 것 같은 예. 응답 후 HTML이 렌더링이 될 때까지의 지연시간이 존재.

동기 처리 : 요청에 따른 응답을 기다린다. HTML 로딩에 문제가 없다.

비동기 처리 : 요청에 따른 응답을 기다리지 않는다. 상황에 따라서 데이터가 완전하지 않은 경우가 발생.

  • <비동기 처리의 문제점>
  1. 이 상황에서 요청을 보내면 불완전한 응답을 받게 된다.
  2. 또한 키보드 입력, 마우스 클릭 등을 requests로는 진행하기 어렵다.
  • <해결방안>
  1. 임의로 시간을 지연한 후, 데이터 처리가 끝난 후 정보를 가져온다.
  2. 키보드 입력, 마우스 클릭 등을 웹 브라우저를 통해 파이썬으로 조작. (Selenium 라이브러리)

💦 공부하며 어려웠던 내용


0개의 댓글