CSS のクラスと ID

Rで学ぶWebスクレイピング

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で学ぶWebスクレイピング

複数クラスを同時に選択

.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で学ぶWebスクレイピング

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で学ぶWebスクレイピング

型で絞り込む

#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')

は次と同等です…

html %>% 
  html_elements('div#special')
Rで学ぶWebスクレイピング

特定の子を選ぶ疑似クラス

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で学ぶWebスクレイピング

まとめ

セレクタ種別 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で学ぶWebスクレイピング

練習しましょう!

Rで学ぶWebスクレイピング

Preparing Video For Download...