CSS třídy a ID

Web Scraping v R

Timo Grossenbacher

Instructor

Třídy

.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 s třídami

html %>% html_elements('.alert')
{xml_nodeset (2)}
[1] <div class="alert">Important text...
[2] <a href="#" class="alert">important ...
Web Scraping v R

Výběr více tříd najednou

.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>
...

Více tříd

html %>% 
    html_elements('.alert.emph') # not: .alert, .emph
{xml_nodeset (1)}
[1] <div class="alert emph">Important text...
Web Scraping v 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>
...

HTML s ID

html %>% 
  html_elements('#special')
{xml_nodeset (1)}
[1] <div id="special">Some text.</div>
Web Scraping v R

Zúžení výběru pomocí typů

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

je ekvivalentní...

html %>% 
  html_elements('div#special')
Web Scraping v R

Pseudotřídy pro výběr konkrétních potomků

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 pseudotřídy

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
Web Scraping v R

Shrnutí...

Typ selektoru HTML CSS selektor
Typ <p>...</p> p
Více typů <p>...</p><div>...</div> p, div
Třída <p class = 'x'>...</p> .x
Více tříd <p class = 'x y'>...</p> .x.y
Typ + třída <p class = 'x'>...</p> p.x
ID <p id = 'x'>...</p> #x
Typ + pseudotřída <p>...</p><p>...</p> p:first-child
Web Scraping v R

Lass uns üben!

Web Scraping v R

Preparing Video For Download...