HTML 표에서 데이터 추출하기
표 형식의 HTML 데이터를 안정적으로 파싱하고 rowspan과 colspan을 처리해 복잡한 표를 깔끔한 구조화 행으로 변환하는 방법을 학습해 보세요.
HTML 표에서 데이터 추출하기은(는) CoddyKit의 무료 Web Scraping & Bots 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Scraping & Bots 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Tables Are Tricky
HTML <table> elements look simple but are one of the most error-prone targets in scraping. Rows can merge cells, headers can repeat, and layout tables masquerade as data tables.
- Data tables hold real records you want.
- Layout tables only control visual structure.
This lesson focuses on extracting clean rows from genuine data tables.
Anatomy of a Table
A table is built from a few key tags:
<thead>/<tbody>group header and body rows.<tr>is a single row.<th>is a header cell,<td>is a data cell.
Knowing these landmarks lets you target rows precisely instead of grabbing raw text.
<table>
<thead><tr><th>Name</th><th>Price</th></tr></thead>
<tbody>
<tr><td>Widget</td><td>$9.99</td></tr>
<tr><td>Gadget</td><td>$14.50</td></tr>
</tbody>
</table>Selecting Rows
With a parser like BeautifulSoup you first find the table, then iterate its rows. Always scope your selection to tbody when present so the header row does not contaminate your data.
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
table = soup.select_one('table')
rows = table.select('tbody tr')
print(len(rows), 'data rows found')Reading Cell Values
For each row, collect the cell text. Use get_text(strip=True) to drop surrounding whitespace and nested tag noise.
for row in rows:
cells = [c.get_text(strip=True) for c in row.select('td')]
print(cells)Mapping Headers to Values
Raw lists of cells are fragile. Pair each value with its column header so your output is self-describing and column-order changes do not break downstream code.
headers = [h.get_text(strip=True) for h in table.select('thead th')]
records = []
for row in rows:
cells = [c.get_text(strip=True) for c in row.select('td')]
records.append(dict(zip(headers, cells)))
print(records[0])Handling colspan
A cell with colspan="2" visually spans two columns. If you ignore it, every following cell shifts left and misaligns with its header. Read the attribute and pad accordingly.
span = int(cell.get('colspan', 1))
values.extend([text] * span)Handling rowspan
rowspan is harder: a cell carries down into rows below it. Track a buffer of pending values keyed by column index and inject them into subsequent rows until the span is exhausted.
pending = {}
for r_idx, row in enumerate(rows):
col = 0
for cell in row.select('td'):
while col in pending and pending[col][1] > 0:
col += 1
rs = int(cell.get('rowspan', 1))
if rs > 1:
pending[col] = [cell.get_text(strip=True), rs]
col += 1Cleaning Extracted Values
Cells often contain currency symbols, thousands separators, or stray unicode. Normalize before storing:
- Strip
$,,and whitespace. - Cast numeric strings to numbers.
- Replace non-breaking spaces.
def clean_price(text):
text = text.replace('$', '').replace(',', '').strip()
return float(text) if text else None
print(clean_price('$1,299.00'))Pandas read_html Shortcut
For well-formed tables, pandas.read_html parses every table on a page into DataFrames in one call. Use it for quick wins, then fall back to manual parsing for tables with merged cells.
import pandas as pd
tables = pd.read_html(html)
df = tables[0]
print(df.head())Detecting Layout vs Data Tables
Before extracting, confirm the table holds real data. Heuristics:
- Has a
<thead>or repeated<th>cells. - Multiple rows with consistent column counts.
- No nested tables used purely for spacing.
Skip tables that fail these checks.
Putting It Together
A robust table extractor: locate the data table, read headers, walk rows while resolving spans, clean each value, and emit a list of dictionaries. This pipeline survives most real-world markup.
def extract_table(table):
headers = [h.get_text(strip=True) for h in table.select('thead th')]
out = []
for row in table.select('tbody tr'):
vals = [c.get_text(strip=True) for c in row.select('td')]
out.append(dict(zip(headers, vals)))
return outQuick Check
Test your understanding of table parsing.
Recap
You learned to extract clean records from HTML tables: scope to tbody, map headers to values, resolve colspan and rowspan, clean cell text, and use pandas.read_html for simple cases.
With these skills you can turn even messy tabular markup into reliable structured data.
자주 묻는 질문
“HTML 표에서 데이터 추출하기” 강의는 무료인가요?
네 — “HTML 표에서 데이터 추출하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Scraping & Bots 강의 전체를 잠금 해제할 수 있습니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.
“HTML 표에서 데이터 추출하기”에서 뭘 배우나요?
표 형식의 HTML 데이터를 안정적으로 파싱하고 rowspan과 colspan을 처리해 복잡한 표를 깔끔한 구조화 행으로 변환하는 방법을 학습해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Web Scraping & Bots을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web Scraping & Bots을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web Scraping & Bots은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“HTML 표에서 데이터 추출하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web Scraping & Bots 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web Scraping & Bots 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 복잡한 HTML 구조 탐색
- 정밀한 CSS 선택자
- 견고한 선택을 위한 XPath
- HTML 표에서 데이터 추출하기