CSS 組合子

R 的網頁爬蟲

Timo Grossenbacher

Instructor

四種不同的組合子

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

space:後代組合子

>:子代組合子

+:相鄰兄弟組合子

~:一般兄弟組合子

R 的網頁爬蟲

後代與子代組合子

<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>
R 的網頁爬蟲

兄弟組合子

<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...
R 的網頁爬蟲

什麼時候用組合子最方便

...
    <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>
R 的網頁爬蟲

一起來練習吧!

R 的網頁爬蟲

Preparing Video For Download...