R Academy · 강의

HTML 구조와 CSS 선택자

DOM 트리를 이해하고 요소를 대상으로 지정하는 CSS 선택자를 작성합니다.

레슨 1/413개 단계

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

HTML DOM 트리

모든 웹 페이지는 문서 객체 모델(DOM) 트리로 구성됩니다. HTML 요소는 서로 안에 중첩되어 부모-자식 계층 구조를 형성합니다. 웹 스크래핑은 이 트리를 탐색하여 데이터를 추출합니다.

# HTML structure conceptually:
# <html>
#   <body>
#     <div class='container'>
#       <h1 id='title'>Hello</h1>
#       <p class='text'>World</p>
#     </div>
#   </body>
# </html>

# rvest lets us query this tree with CSS selectors
library(rvest)
html <- read_html('<div><h1>Title</h1><p class="info">Text</p></div>')
html_text(html_element(html, 'h1'))

CSS 선택자: 태그 선택자

가장 간단한 CSS 선택자는 태그 이름으로 요소를 대상으로 지정합니다. p를 작성하면 모든 단락 요소를 선택합니다. h1을 작성하면 모든 1단계 제목을 선택합니다.

library(rvest)
html <- read_html('
  <div>
    <p>First paragraph</p>
    <p>Second paragraph</p>
    <h2>A heading</h2>
  </div>
')
# Tag selector: selects all <p> elements
nodes <- html_elements(html, 'p')
html_text2(nodes)
# Returns: c('First paragraph', 'Second paragraph')

CSS 선택자: 클래스와 ID

.classname을 사용하면 클래스로 요소를 선택하고, #idname을 사용하면 ID로 고유한 요소를 선택합니다. 클래스는 여러 번 나타날 수 있지만 ID는 페이지에서 고유해야 합니다.

library(rvest)
html <- read_html('
  <div>
    <p class="highlight">Important text</p>
    <p class="normal">Regular text</p>
    <span id="price">$9.99</span>
  </div>
')
# Class selector (prefix with .)
html_text2(html_element(html, '.highlight'))
# ID selector (prefix with #)
html_text2(html_element(html, '#price'))

하위 요소 및 자식 요소 선택자

div p는 div 안의 모든 깊이에 있는 p를 선택합니다. div > p는 직접 자식만 선택합니다. h1 + p는 h1 바로 뒤에 오는 p를 선택합니다(인접 형제).

library(rvest)
html <- read_html('
  <div class="outer">
    <p>Direct child</p>
    <section>
      <p>Nested deeper</p>
    </section>
  </div>
')
# Descendant: both paragraphs
all_p <- html_elements(html, 'div p')
length(all_p)  # 2

# Direct child only
direct_p <- html_elements(html, 'div.outer > p')
length(direct_p)  # 1

속성 선택자

CSS 속성 선택자를 사용하면 HTML 속성으로 필터링할 수 있습니다. [attr]은 존재 여부를 확인하고, [attr='val']은 정확한 값을 확인하며, [attr*='val']은 값에 부분 문자열이 포함되어 있는지 확인합니다.

library(rvest)
html <- read_html('
  <div>
    <a href="https://example.com">External</a>
    <a href="/about">Internal</a>
    <a>No href</a>
  </div>
')
# Select only anchors that have an href attribute
with_href <- html_elements(html, 'a[href]')
length(with_href)  # 2

# Select anchors with href starting with https
external <- html_elements(html, 'a[href^="https"]')
html_text2(external)  # 'External'

XPath 기초

XPath는 CSS 선택자의 대안이며 복잡한 쿼리에 더 강력합니다. rvest에서는 html_element(html, xpath='//tag')를 사용합니다. //p는 어디에 있든 모든 p를 의미하고, /html/body/p는 절대 경로입니다.

library(rvest)
html <- read_html('
  <html><body>
    <table>
      <tr><td class="price">10.99</td></tr>
      <tr><td class="price">5.50</td></tr>
    </table>
  </body></html>
')
# XPath: select all td with class price
nodes <- html_elements(html, xpath = '//td[@class="price"]')
html_text2(nodes)
# c('10.99', '5.50')

# XPath text() function
nodes2 <- html_elements(html, xpath = '//td[contains(@class,"price")]')
html_text2(nodes2)

선택자 결합하기

정밀하게 선택하기 위해 선택자를 결합할 수 있습니다. div.card h2는 클래스가 card인 div 안의 h2를 선택합니다. 쉼표는 서로 독립적인 여러 선택자를 구분합니다. h1, h2, h3은 세 단계의 제목을 모두 선택합니다.

library(rvest)
html <- read_html('
  <div class="card">
    <h2>Card Title</h2>
    <p class="desc">Description here</p>
    <span class="price">$19</span>
  </div>
  <div class="footer">
    <h2>Footer Heading</h2>
  </div>
')
# Only h2 inside .card
card_h2 <- html_element(html, 'div.card h2')
html_text2(card_h2)  # 'Card Title'

# Multiple selectors with comma
price_desc <- html_elements(html, '.price, .desc')
html_text2(price_desc)

SelectorGadget 도구

SelectorGadget은 CSS 선택자를 대화형으로 찾도록 도와주는 브라우저 북마클릿입니다. 원하는 요소(녹색으로 강조됨)와 원하지 않는 요소(빨간색으로 강조됨)를 클릭하면 최소 CSS 선택자를 자동으로 생성합니다.

# SelectorGadget workflow:
# 1. Open target page in Chrome/Firefox
# 2. Activate SelectorGadget bookmarklet
# 3. Click element you want -> turns green, selector appears
# 4. Click elements you DON'T want -> turns red, selector narrows
# 5. Copy the selector shown at the bottom
# 6. Use in rvest:

library(rvest)
# Example: SelectorGadget found '.product-title' for us
# page <- read_html('https://books.toscrape.com')
# titles <- html_elements(page, '.product_pod h3 a')
# html_text2(titles)
cat('SelectorGadget is available at selectorgadget.com')

DevTools에서 페이지 검사하기

브라우저 DevTools(F12)를 사용하면 DOM을 직접 검사할 수 있습니다. 요소를 마우스 오른쪽 버튼으로 클릭하고 검사를 선택하면 요소 패널에 HTML이 표시됩니다. 마우스를 올리면 페이지의 요소가 강조되어 대상으로 삼을 정확한 태그, 클래스, ID를 식별하는 데 도움이 됩니다.

# DevTools workflow for finding selectors:
# 1. F12 -> Elements tab
# 2. Click the cursor icon (Inspector)
# 3. Click the element on the page
# 4. Right-click highlighted HTML -> Copy -> Copy selector
# 5. Paste selector into rvest

# The copied selector might look like:
# '#main > div.results > article:nth-child(1) > h3'
# Simplify it: usually '.results h3' works just as well

# Validate your selector in the Console with:
# document.querySelectorAll('.results h3')
library(rvest)
cat('Always verify selectors return the elements you expect')

의사 클래스와 nth-child

:first-child, :last-child, :nth-child(n)과 같은 CSS 의사 클래스를 사용하면 부모 요소 안에서의 위치를 기준으로 요소를 선택할 수 있습니다. 요소를 구분하는 클래스가 없을 때 유용합니다.

library(rvest)
html <- read_html('
  <ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
  </ul>
')
# First item
first <- html_element(html, 'li:first-child')
html_text2(first)  # 'First'

# Third item
third <- html_element(html, 'li:nth-child(3)')
html_text2(third)  # 'Third'

# Even items
evens <- html_elements(html, 'li:nth-child(even)')
html_text2(evens)  # c('Second', 'Fourth')

선택자 우선순위 규칙

여러 선택자가 일치할 수 있을 때는 우선순위에 따라 어떤 선택자가 적용될지 결정됩니다. ID가 클래스보다 우선하고, 클래스가 태그보다 우선합니다. 스크래핑에서는 이 점이 덜 중요하지만, 우선순위를 알면 잘못된 일치를 피하는 정확한 선택자를 작성할 수 있습니다.

library(rvest)
html <- read_html('
  <div id="header" class="top">
    <p class="title">Main Title</p>
  </div>
  <div class="content">
    <p class="title">Content Title</p>
  </div>
')
# Overly broad: gets BOTH titles
broad <- html_elements(html, 'p.title')
html_text2(broad)

# Specific: only header title
specific <- html_element(html, '#header p.title')
html_text2(specific)  # 'Main Title'

# Be as specific as needed but not more
content_title <- html_element(html, '.content .title')
html_text2(content_title)

빠른 확인

rvest에서 웹 스크래핑에 사용하는 CSS 선택자에 대한 이해도를 확인해 보세요.

복습: HTML 및 CSS 선택자

핵심 요점: DOM은 트리 구조이며 CSS 선택자로 트리를 탐색합니다. 요소 유형에는 tag, 클래스에는 .class, 고유한 요소에는 #id, 직접적인 자식 요소에는 >, 속성에는 [attr]을 사용합니다. SelectorGadget과 DevTools를 사용하면 대화형 방식으로 선택자를 찾을 수 있습니다. CSS로 처리하기 어려운 경우에는 XPath(//tag[@attr])를 사용합니다.

# Summary of key CSS selectors for web scraping:
# 'p'            -> all <p> elements
# '.price'       -> elements with class='price'
# '#main'        -> element with id='main'
# 'div > p'      -> direct child p of div
# 'a[href]'      -> a elements that have href attr
# 'a[href*=http] -> a elements where href contains 'http'
# 'li:nth-child(2)' -> second li in its parent
# 'h1, h2'       -> both h1 and h2 elements
# xpath='//td[@class="price"]' -> XPath alternative
library(rvest)
cat('Selectors are the foundation of reliable web scraping')
무료로 시작

AI 튜터와 함께 R을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
43
레슨
159

자주 묻는 질문

“HTML 구조와 CSS 선택자” 강의는 무료인가요?

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

“HTML 구조와 CSS 선택자”에서 뭘 배우나요?

DOM 트리를 이해하고 요소를 대상으로 지정하는 CSS 선택자를 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 R Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“HTML 구조와 CSS 선택자” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. HTML 구조와 CSS 선택자
  2. html_element()와 html_text() 기초
  3. 테이블과 링크 스크래핑
  4. 페이지 매김과 여러 페이지 처리
← R Academy(으)로 돌아가기