rvest: Filter node based on inner class text and count number of svg elements inside

Viewed 522

My HTML looks like:

<div class="rates">
    <div class="rate">
        <span class="title">A</span>
        <img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"> 
    </div>
    <div class="rate">
        <span class="title">B</span>
        <img src="y.svg" alt="" width="20"><img src="y.svg" alt="" width="20"> 
    </div>
</div>

I would like get counts of x.svg in A and counts of y.svg in B. So:

A: 3
B: 2

I have 2 problems:
1. If I use html_nodes(".rate") I get both but don't know how to filter based on title text.
2. Count number of occurences of .svg elements.

1 Answers

Here is possible solution by finding all of the parent rate nodes and then counting the number of img nodes per parent.

library(rvest)
library(magrittr)

page<-read_html('<div class="rates">
    <div class="rate">
        <span class="title">A</span>
        <img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"><img src="x.svg" alt="" width="20"> 
    </div>
    <div class="rate">
        <span class="title">B</span>
        <img src="y.svg" alt="" width="20"><img src="y.svg" alt="" width="20"> 
    </div>
</div>')

#find all of the parent nodes
  ratenodes <- page %>% html_nodes("div.rate")

#find a single title node per parent
  titles <- ratenodes %>% html_node("span.title") %>% html_text()
#Count the number of img nodes per parent.
  imagecount <- sapply(ratenodes, function(node) { 
         node %>% html_nodes("img") %>% length()})

answer<-data.frame(titles, imagecount)
Related