[python] Beautiful Soup 문법

Beautiful Soup은 웹 스크래핑을 위해 사용되는 Python 라이브러리입니다. 이 라이브러리를 사용하면 HTML 또는 XML 문서에서 원하는 데이터를 추출할 수 있습니다. Beautiful Soup은 검색, 탐색, 수정 등 다양한 기능을 제공하여 스크래핑 작업을 효과적으로 수행할 수 있습니다.

설치

Beautiful Soup을 사용하기 위해선 먼저 관련 패키지를 설치해야 합니다. 다음 명령어를 사용하여 설치할 수 있습니다.

pip install beautifulsoup4

기본 사용법

Beautiful Soup 객체를 생성하고, 이 객체를 이용하여 원하는 데이터를 추출할 수 있습니다.

HTML 파싱

from bs4 import BeautifulSoup

html_doc = """
<html>
<head>
    <title>Beautiful Soup Example</title>
</head>
<body>
    <h1>HTML 문서 예제</h1>
    <p>Beautiful Soup을 이용한 웹 스크래핑</p>
    <ul>
        <li>리스트 1</li>
        <li>리스트 2</li>
        <li>리스트 3</li>
    </ul>
</body>
</html>
"""

soup = BeautifulSoup(html_doc, 'html.parser')

# h1 태그의 텍스트 가져오기
title = soup.h1.text
print(title)  # 출력: "HTML 문서 예제"

# p 태그의 텍스트 가져오기
paragraph = soup.p.text
print(paragraph)  # 출력: "Beautiful Soup을 이용한 웹 스크래핑"

# ul 태그의 모든 li 태그 가져오기
list_items = soup.ul.find_all('li')
for li in list_items:
    print(li.text)  # 출력: "리스트 1", "리스트 2", "리스트 3"

CSS 선택자를 이용한 데이터 추출

Beautiful Soup은 CSS 선택자를 이용하여 원하는 데이터를 추출할 수도 있습니다.

from bs4 import BeautifulSoup

html_doc = """
<html>
<head>
    <title>Beautiful Soup Example</title>
</head>
<body>
    <h1>HTML 문서 예제</h1>
    <div id="content">
        <p>Beautiful Soup을 이용한 웹 스크래핑</p>
        <ul class="my-list">
            <li>리스트 1</li>
            <li>리스트 2</li>
            <li>리스트 3</li>
        </ul>
    </div>
    <div class="footer">
        <p>Copyright © 2022</p>
    </div>
</body>
</html>
"""

soup = BeautifulSoup(html_doc, 'html.parser')

# id가 'content'인 div 태그 내의 p 태그의 텍스트 가져오기
content = soup.select_one('#content > p').text
print(content)  # 출력: "Beautiful Soup을 이용한 웹 스크래핑"

# class가 'my-list'인 ul 태그 내의 모든 li 태그 가져오기
list_items = soup.select('.my-list > li')
for li in list_items:
    print(li.text)  # 출력: "리스트 1", "리스트 2", "리스트 3"

참고 자료