BeautifulSoup으로 데이터 추출
BeautifulSoup을 사용해 HTML 문서를 분석하고 태그, 클래스 및 ID로 특정 데이터 항목을 추출합니다.
BeautifulSoup으로 데이터 추출은(는) CoddyKit의 무료 Web Scraping & Bots 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Scraping & Bots 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
BeautifulSoup: Your HTML Navigator
You've learned to fetch web page content using requests. But that content is just a big string of HTML!
BeautifulSoup is a Python library that helps you parse (understand) that HTML. It turns the raw HTML into a tree-like structure, making it easy to navigate and extract specific data.
Why Use a Parser?
Imagine trying to find a specific sentence in a book without page numbers or chapters. That's like trying to extract data from raw HTML strings!
BeautifulSoup gives structure to the HTML, allowing you to easily locate elements like headings, paragraphs, or links using their tags, classes, or IDs.
Creating a BeautifulSoup Object
First, you need to import the library and create a BeautifulSoup object. You pass your HTML content and specify a parser, usually 'html.parser'.
from bs4 import BeautifulSoup
html_doc = """<html><head><title>My Page</title></head><body><h1>Hello</h1><p>World</p></body></html>"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())Finding Elements by Tag
The simplest way to find elements is by their HTML tag name. You can use soup.find() to get the first matching tag or soup.find_all() to get all matching tags.
find('tag_name'): Returns a single Tag object orNone.find_all('tag_name'): Returns a list of Tag objects.
Code: Finding Tags
Let's find the <title> and all <p> tags in our example HTML.
from bs4 import BeautifulSoup
html_doc = """<html><head><title>My Page</title></head><body><h1>Welcome!</h1><p class='intro'>This is an intro.</p><p>Another paragraph.</p></body></html>"""
soup = BeautifulSoup(html_doc, 'html.parser')
# Find the first title tag
title_tag = soup.find('title')
print(f"Title tag: {title_tag}")
# Find all paragraph tags
paragraph_tags = soup.find_all('p')
print(f"Paragraph tags found: {len(paragraph_tags)}")
for p in paragraph_tags:
print(f" - {p.get_text()}")Extracting Text and Attributes
Once you have a Tag object, you can easily get its text content or attribute values.
- To get text: Use the
.get_text()method. - To get attributes: Access them like a dictionary, e.g.,
tag['href']ortag.get('href').
Code: Getting Text and Attributes
Let's extract the text from the <h1> and an attribute from a link.
from bs4 import BeautifulSoup
html_doc = """<html><body><h1 id='main-h1'>Hello CoddyKit</h1><a href='https://example.com' class='btn'>Visit Example</a></body></html>"""
soup = BeautifulSoup(html_doc, 'html.parser')
h1_tag = soup.find('h1')
print(f"H1 Text: {h1_tag.get_text()}")
link_tag = soup.find('a')
print(f"Link Text: {link_tag.get_text()}")
print(f"Link Href: {link_tag['href']}")
print(f"Link Class: {link_tag['class']}")Finding Elements by Class
Web pages often use CSS classes to style and identify elements. BeautifulSoup lets you search for elements with a specific class using the class_ argument.
Why class_ and not class? Because class is a reserved keyword in Python!
Code: Finding by Class
Here's how to find paragraphs specifically marked with class="intro".
from bs4 import BeautifulSoup
html_doc = """<html><body><p class='intro'>Welcome message.</p><p>Normal text.</p><p class='intro'>Another intro.</p></body></html>"""
soup = BeautifulSoup(html_doc, 'html.parser')
intro_paragraphs = soup.find_all('p', class_='intro')
for p in intro_paragraphs:
print(f"Found intro: {p.get_text()}")Finding Elements by ID
HTML IDs are unique identifiers for elements within a page. You can target a specific element using its ID with the id argument.
Since IDs should be unique per page, find() is often sufficient when searching by ID.
Quick Check: Element Selection
Given the HTML snippet below, how would you extract the text 'Item 2'?
<div id="items">
<span class="item-name">Item 1</span>
<span class="item-name">Item 2</span>
<span class="item-name">Item 3</span>
</div>Recap: BeautifulSoup Basics
Great job! You've learned the fundamentals of extracting data using BeautifulSoup:
- Initializing a
BeautifulSoupobject from HTML. - Finding elements by tag name using
find()andfind_all(). - Extracting text content with
.get_text()and attributes withtag['attr']. - Targeting elements precisely using CSS classes with
class_. - Locating unique elements with IDs using
id.
These methods are your building blocks for parsing web pages efficiently!
자주 묻는 질문
“BeautifulSoup으로 데이터 추출” 강의는 무료인가요?
네 — “BeautifulSoup으로 데이터 추출” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Scraping & Bots 강의 전체를 잠금 해제할 수 있습니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.
“BeautifulSoup으로 데이터 추출”에서 뭘 배우나요?
BeautifulSoup을 사용해 HTML 문서를 분석하고 태그, 클래스 및 ID로 특정 데이터 항목을 추출합니다. 브라우저에서 직접 실행하는 실습 코드로 Web Scraping & Bots을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web Scraping & Bots을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web Scraping & Bots은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“BeautifulSoup으로 데이터 추출” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web Scraping & Bots 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web Scraping & Bots 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 환경 설정
- URL에 Requests 사용
- BeautifulSoup으로 데이터 추출
- CSS 선택자로 DOM 탐색하기