CSS 클래스와 ID

R로 배우는 웹 스크레이핑

Timo Grossenbacher

Instructor

클래스

.alert {
  color: red;
  font-weight: 800;
}
...
<div>Some text.</div>
<div class = 'alert'>Important text.</div>  
<div>
  Some text with an
  <a href = '#' class = 'alert'>important link</a>.
</div>
...

클래스가 있는 HTML

html %>% html_elements('.alert')
{xml_nodeset (2)}
[1] <div class="alert">Important text...
[2] <a href="#" class="alert">important ...
R로 배우는 웹 스크레이핑

여러 클래스를 한꺼번에 선택

.alert {
  color: red;
  font-weight: 800;
}
.emph {
  font-style: italic;
}
...
<div>Some text.</div>
<div class = 'alert emph'>Important text.</div>  
<div>
  Some text with an
  <a href = '#' class = 'alert'>important link</a>.
</div>
...

다중 클래스

html %>% 
    html_elements('.alert.emph') # 올바름, .alert, .emph 아님
{xml_nodeset (1)}
[1] <div class="alert emph">Important text...
R로 배우는 웹 스크레이핑

ID

#special {
  color: green;
}
.alert {
  color: red;
  font-weight: 800;
}
...
<div id = 'special'>Some text.</div>
<div class = 'alert'>Important text.</div>  
<div>
  Some text with an
  <a href = '#' class = 'alert'>important link</a>.
</div>
...

ID가 있는 HTML

html %>% 
  html_elements('#special')
{xml_nodeset (1)}
[1] <div id="special">Some text.</div>
R로 배우는 웹 스크레이핑

태그로 선택 범위 좁히기

#special {
  color: green;
}
.alert {
  color: red;
  font-weight: 800;
}
...
<div id = 'special'>Some text.</div>
<div class = 'alert'>Important text.</div>  
<div>
  Some text with an
  <a href = '#' class = 'alert'>important link</a>.
</div>
...
html %>% 
  html_elements('a.alert')
{xml_nodeset (1)}
[1] <a href="#" class="alert">important ...
html %>% 
  html_elements('#special')

is equivalent to...

html %>% 
  html_elements('div#special')
R로 배우는 웹 스크레이핑

특정 자식을 고르는 의사 클래스

li:first-child { color: blue; }

li:nth-child(2) { color: green; }

li:last-child { color: red; }
...
<ol>
  <li>First element.</li>
  <li>Second element.</li>
  <li>Third element.</li>
</ol>
...

CSS 의사 클래스

html %>% html_elements('li:last-child') 
    # 또는 html_elements('li:nth-child(3)')
{xml_nodeset (1)}
[1] <li>Third element.</li>
1 https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
R로 배우는 웹 스크레이핑

정리

선택자 유형 HTML CSS 선택자
태그 <p>...</p> p
여러 태그 <p>...</p><div>...</div> p, div
클래스 <p class = 'x'>...</p> .x
다중 클래스 <p class = 'x y'>...</p> .x.y
태그 + 클래스 <p class = 'x'>...</p> p.x
ID <p id = 'x'>...</p> #x
태그 + 의사 클래스 <p>...</p><p>...</p> p:first-child
R로 배우는 웹 스크레이핑

Ayo berlatih!

R로 배우는 웹 스크레이핑

Preparing Video For Download...