0Pricing
AI Agents · 강의

BeautifulSoup으로 HTML 파싱하기

find(), select(), CSS 선택자, HTML에서 구조화된 콘텐츠 추출을 알아봅니다.

BeautifulSoup으로 HTML 파싱하기은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

에이전트에서 HTML을 구문 분석하는 이유

많은 데이터 소스는 API가 아니라 웹 페이지입니다. 에이전트가 HTML에서 구조화된 정보를 추출해야 할 때는 원시 마크업을 탐색 가능한 트리로 구문 분석해야 합니다.

BeautifulSoup(bs4)는 이를 위한 표준 Python 라이브러리입니다. 복잡한 HTML을 쉽게 조회할 수 있는 Python 객체로 변환합니다.

BeautifulSoup 객체 만들기

원시 HTML과 파서 이름을 BeautifulSoup()에 전달합니다. 'html.parser'는 Python에 내장되어 있어 별도로 설치할 필요가 없습니다. 큰 페이지를 더 빠르게 구문 분석하려면 pip를 통해 'lxml'을 사용할 수 있습니다.

from bs4 import BeautifulSoup
import httpx

# Fetch HTML
response = httpx.get('https://example.com', timeout=10.0)
html = response.text

# Parse it
soup = BeautifulSoup(html, 'html.parser')

# Get the page title
print(soup.title.text)  # 'Example Domain'

find() — 단일 요소 찾기

soup.find(tag, attrs)는 일치하는 첫 번째 요소를 반환하고, 찾지 못하면 None을 반환합니다. 태그 이름, 클래스, ID 또는 모든 속성을 기준으로 일치시킬 수 있습니다.

결과에 대해 메서드를 호출하기 전에 항상 None인지 확인합니다.

from bs4 import BeautifulSoup

html = '<div class="content"><h1>Title</h1><p>Body text here.</p></div>'
soup = BeautifulSoup(html, 'html.parser')

# Find by tag + class
content_div = soup.find('div', class_='content')
if content_div:
    heading = content_div.find('h1')
    print(heading.text)  # 'Title'

# Find by id
sidebar = soup.find('div', id='sidebar')  # None if absent

find_all() — 여러 요소 찾기

soup.find_all(tag)는 일치하는 모든 요소의 목록을 반환합니다. 목록 항목, 표 행 또는 기사 카드처럼 반복되는 구조에서 데이터를 추출하려면 이 목록을 순회합니다.

from bs4 import BeautifulSoup

html = '<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>'
soup = BeautifulSoup(html, 'html.parser')

items = soup.find_all('li')
for item in items:
    print(item.text)  # Apple, Banana, Cherry

# Limit results
first_two = soup.find_all('li', limit=2)

select()를 사용한 CSS 선택자

soup.select('css selector')를 사용하면 익숙한 CSS 구문을 이용할 수 있습니다. 특히 중첩된 요소를 다룰 때 여러 find() 호출을 연결하는 것보다 간결한 경우가 많습니다.

from bs4 import BeautifulSoup

html = '''
<table>
  <tr><td class="name">Alice</td><td class="score">95</td></tr>
  <tr><td class="name">Bob</td><td class="score">87</td></tr>
</table>
'''
soup = BeautifulSoup(html, 'html.parser')

# Select all td elements inside tr inside table
cells = soup.select('table tr td')
for cell in cells:
    print(cell.text)

# Select only name cells
names = soup.select('td.name')
for n in names:
    print(n.text)  # Alice, Bob

.text와 .strip()으로 텍스트 추출하기

.text(또는 .get_text())는 중첩된 태그를 포함해 요소 내부의 모든 텍스트 콘텐츠를 반환합니다. HTML에 자주 포함되는 앞뒤 공백을 제거하려면 .strip()을 사용합니다.

from bs4 import BeautifulSoup

html = '<p>  \n  Price: <strong>$29.99</strong>  \n  </p>'
soup = BeautifulSoup(html, 'html.parser')

paragraph = soup.find('p')

# .text includes nested tag content
print(paragraph.text)          # '  \n  Price: $29.99  \n  '
print(paragraph.text.strip())  # 'Price: $29.99'

# get_text with separator
print(paragraph.get_text(separator=' ', strip=True))  # 'Price: $29.99'

.get()으로 속성 추출하기

href, src, data-*와 같은 태그 속성은 .get('attr_name')을 사용해 사전처럼 접근합니다. 속성이 없으면 안전하게 None을 반환합니다.

from bs4 import BeautifulSoup

html = '''
<a href="https://example.com/page" data-id="42">Click here</a>
<img src="/images/logo.png" alt="Logo">
'''
soup = BeautifulSoup(html, 'html.parser')

link = soup.find('a')
print(link.get('href'))     # 'https://example.com/page'
print(link.get('data-id'))  # '42'
print(link.get('class'))    # None (no class attribute)

img = soup.find('img')
print(img.get('src'))       # '/images/logo.png'

구문 분석 트리 탐색하기

BeautifulSoup 요소에는 탐색할 수 있는 부모/자식/형제 관계가 있습니다. .parent, .children, .next_sibling, .previous_sibling을 사용해 찾은 요소 주변을 탐색합니다.

from bs4 import BeautifulSoup

html = '''
<div class="article">
  <h2>Headline</h2>
  <p>First paragraph.</p>
  <p>Second paragraph.</p>
</div>
'''
soup = BeautifulSoup(html, 'html.parser')

h2 = soup.find('h2')
print(h2.text)                    # 'Headline'
print(h2.parent['class'])         # ['article']
print(h2.next_sibling.next_sibling.text)  # 'First paragraph.'

페이지에서 모든 링크 추출하기

에이전트의 일반적인 작업 중 하나는 추가 크롤링을 위해 페이지의 모든 링크를 수집하는 것입니다. 모든 <a> 태그를 찾고 해당 href 속성을 추출한 다음 비어 있는 항목을 제외합니다.

from bs4 import BeautifulSoup
import httpx

def extract_links(url: str) -> list:
    response = httpx.get(url, timeout=10.0)
    soup = BeautifulSoup(response.text, 'html.parser')

    links = []
    for tag in soup.find_all('a'):
        href = tag.get('href')
        if href and href.startswith('http'):
            links.append(href)
    return links

# urls = extract_links('https://news.ycombinator.com')
# print(urls[:5])

잘못된 HTML을 안정적으로 처리하기

실제 환경의 HTML은 닫히지 않은 태그, 일치하지 않는 요소, 인코딩 문제 등으로 손상된 경우가 많습니다. BeautifulSoup의 파서는 유연하게 이러한 문제를 처리하며 오류를 자동으로 수정하려고 시도합니다. 하지만 중첩된 요소에 접근할 때는 항상 None에 대비해야 합니다.

from bs4 import BeautifulSoup

# Broken HTML — missing closing tags
html = '<div><p>Hello <strong>World</div>'
soup = BeautifulSoup(html, 'html.parser')

# BS4 repairs the tree automatically
print(soup.prettify())
# <div><p>Hello <strong>World</strong></p></div>

# Safe chained access
price = soup.find('span', class_='price')
price_text = price.text.strip() if price else 'N/A'
print(price_text)  # 'N/A'

완전한 에이전트 스크레이퍼 도구

이제 모든 내용을 하나로 결합해 보겠습니다. 다음은 에이전트가 도구로 호출할 수 있는 완전한 스크레이퍼 함수입니다. 페이지를 가져와 구문 분석한 뒤 에이전트가 추론할 수 있는 형식으로 구조화된 데이터를 반환합니다.

from bs4 import BeautifulSoup
import httpx

def scrape_article(url: str) -> dict:
    response = httpx.get(url, headers={'User-Agent': 'MyAgent/1.0'}, timeout=10.0)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')

    title = soup.find('h1')
    paragraphs = soup.find_all('p')

    return {
        'url': url,
        'title': title.text.strip() if title else '',
        'text': ' '.join(p.text.strip() for p in paragraphs[:5]),
        'links': [a.get('href') for a in soup.find_all('a', href=True)][:10]
    }

지식 확인: BeautifulSoup

BeautifulSoup을 사용한 HTML 파싱에 대한 이해도를 확인해 보세요.

복습: BeautifulSoup으로 HTML 파싱하기

이제 에이전트 내부의 HTML 페이지에서 구조화된 데이터를 추출할 수 있습니다.

  • BeautifulSoup(html, 'html.parser')로 수프 객체 만들기
  • 단일 요소에는 find()를, 여러 요소에는 find_all() 사용하기
  • CSS 선택자 쿼리에는 select() 사용하기
  • .text.strip()로 텍스트를 가져오고 .get('attr')로 속성 가져오기
  • .parent, .children 및 형제 요소를 사용해 트리 탐색하기

HTTP 클라이언트와 결합하면 BeautifulSoup을 통해 에이전트가 모든 웹 페이지를 읽을 수 있습니다.

자주 묻는 질문

“BeautifulSoup으로 HTML 파싱하기” 강의는 무료인가요?

네 — “BeautifulSoup으로 HTML 파싱하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

“BeautifulSoup으로 HTML 파싱하기”에서 뭘 배우나요?

find(), select(), CSS 선택자, HTML에서 구조화된 콘텐츠 추출을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Agents을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“BeautifulSoup으로 HTML 파싱하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 에이전트용 HTTP 클라이언트: httpx와 requests
  2. BeautifulSoup으로 HTML 파싱하기
  3. 페이지 매김 및 동적 콘텐츠 처리
  4. 예의를 지키는 스크래핑 관행
← AI Agents(으)로 돌아가기