CSS combinators

Web Scraping in R

Timo Grossenbacher

Instructor

There are four different combinators

Structure: h2#someid {space|>|+|~} .someclass

space: Descendant combinator

>: Child combinator

+: Adjacent sibling combinator

~: General sibling combinator

Web Scraping in R

The descendant and child combinators

<html>
  <body>
    <div class = 'first'>
      <a>A link.</a>
      <p>The first paragraph with 
        <a>another link</a>.
      </p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
  </body>
</html>
html %>% 
    html_elements('div.first a')
{xml_nodeset (2)}
[1] <a>A link.</a>
[2] <a>another link</a>
html %>% 
    html_elements('div.first > a')
{xml_nodeset (1)}
[1] <a>A link.</a>
Web Scraping in R

The sibling combinators

<html>
  <body>
    <div class = 'first'>
      <a>A link.</a>
      <p>The first paragraph with 
        <a>another link</a>.
      </p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
    <p>A paragraph.</p>
  </body>
</html>
html %>% html_elements('div.first + div')
{xml_nodeset (1)}
[1] <div>\n Not an actual...
html %>% html_elements('div.first ~ div')
{xml_nodeset (1)}
[1] <div>\n Not an actual...
html %>% html_elements('div.first ~ *')
{xml_nodeset (2)}
[1] <div>\n Not an actual... [2] <p>A paragraph...
Web Scraping in R

When combinators come in handy

...
    <div id = 'start'>
      <h1 class = 'first'>First</h1>
    </div>
    <div id = 'end'>
      <p class = 'text1'>Some text.</p>
      <p class = 'text2'>More text.</p>
    </div>
...
html %>% html_elements('.text2')
{xml_nodeset (1)}
[1] <p class="text2">More text.</p>
...
    <div>
      <h1>First</h1>
    </div>
    <div>
      <p>Some text.</p>
      <p>More text.</p>
    </div>
...
html %>% html_elements('p + p')
{xml_nodeset (1)}
[1] <p>More text.</p>
Web Scraping in R

Let's practice!

Web Scraping in R

Preparing Video For Download...