CSS 类与 ID

R 语言网页抓取

Timo Grossenbacher

Instructor

类(Class)

.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') # not: .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') 
    # or 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 语言网页抓取

小结

Selector type HTML CSS selector
Type <p>...</p> p
Multiple types <p>...</p><div>...</div> p, div
Class <p class = 'x'>...</p> .x
Multiple classes <p class = 'x y'>...</p> .x.y
Type + Class <p class = 'x'>...</p> p.x
ID <p id = 'x'>...</p> #x
Type + Pseudo-class <p>...</p><p>...</p> p:first-child
R 语言网页抓取

¡Vamos a practicar!

R 语言网页抓取

Preparing Video For Download...