Naviguer dans le HTML

Extraction de données Web en R

Timo Grossenbacher

Instructor

Le HTML, c'est comme un arbre

<html>
  <body>
    <div>
      <p>The first paragraph.</p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
    <p>A paragraph without an 
      enclosing div.</p>
  </body>
</html>

Arborescence HTML

Extraction de données Web en R

Le HTML, c'est comme un arbre

<html>
  <body>
    <div>
      <p>The first paragraph.</p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
    <p>A paragraph without an 
      enclosing div.</p>
  </body>
</html>

Arborescence HTML 2

Extraction de données Web en R

Le HTML, c'est comme un arbre

<html>
  <body>
    <div>
      <p>The first paragraph.</p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
    <p>A paragraph without an 
      enclosing div.</p>
  </body>
</html>

Arborescence HTML 3

Extraction de données Web en R

Parcourir l'arbre avec rvest

<html>
  <body>
    <div>
      <p>The first paragraph.</p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
    <p>A paragraph without an 
      enclosing div.</p>
  </body>
</html>
html <- read_html(html_document)

html_children(html)
{xml_nodeset (1)}
[1] <body>\n    <div>\n  < ...
html %>% html_children()
html %>% html_children() %>% html_text()
[1] "\n    \n      The first paragraph.\n   
\n    \n      Not an actual paragraph, \n      
but with a link.\n    \n    A paragraph ...
Extraction de données Web en R

Atteindre des nœuds avec des sélecteurs

<html>
  <body>
    <div>
      <p>The first paragraph.</p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
    <p>A paragraph without an 
      enclosing div.</p>
  </body>
</html>
html <- read_html(html_document)

html %>% html_element('body')
{xml_nodeset (1)}
[1] <body>\n    <div>\n  < ...
html %>% html_elements('div p')
{xml_nodeset (1)}
[1] <p>The first paragraph.</p>
Extraction de données Web en R

Atteindre des nœuds avec des sélecteurs

<html>
  <body>
    <div>
      <p>The first paragraph.</p>
    </div>
    <div>
      Not an actual paragraph, 
      but with a <a href="#">link</a>.
    </div>
    <p>A paragraph without an 
      enclosing div.</p>
  </body>
</html>
html %>% html_elements('p')
{xml_nodeset (2)}
[1] <p>The first paragraph.</p>
[2] <p>A paragraph without an enclosi...
html %>% html_elements('div') %>% 
    html_elements('p')
{xml_nodeset (1)}
[1] <p>The first paragraph.</p>
Extraction de données Web en R

Extraire des attributs

html %>%
    html_element('a') %>%
    html_attr('href')
[1] #
html %>%
    html_element('a') %>%
    html_attrs()
href 
 "#"
Extraction de données Web en R

Allons-y !

Extraction de données Web en R

Preparing Video For Download...