rvest:处理不同数量的嵌套 类

rvest: handling different number of nested classes

我不确定如何描述问题,所以我将直接转到示例。
我有一个 HTML 文档 (html_doc),看起来像:

<div class="main">
   <h2>A</h2>
   <div class="route">
      X<br />
   </div>
   <div class="route">
      Y<br />
   </div>
</div>
<div class="main">
   <h2>B</h2>
   <div class="route">
      Z<br />
   </div>
</div>

在每个 main 中,titleroute 旁边还有更多元素,因此我正在寻找可扩展的解决方案。 类 在 main 中总是相同的。
我想要一个看起来像这样的小标题:

id | title | route
1  | A     | X
1  | A     | Y
2  | B     | Z 

我当前的尝试出错,因为 titleroute 中的行数不同。我也不知道如何索引 class main.

tibble(
  title = html_doc %>% html_nodes("h2") %>% html_text(), 
  route = html_doc %>% html_nodes(".route") %>% html_text()
  ) 

这遵循与您上一个问题类似的策略。诀窍是遍历每个 child 节点,创建一个单独的 data.frame 标题和路线,然后将所有单独的数据帧组合到最终结果中。
此解决方案确实依赖于每个节点只有 1 个标题。

library(rvest)
library(dplyr)

page<-read_html('<<div class="main">
   <h2>A</h2>
   <div class="route">
      X<br />
   </div>
   <div class="route">
      Y<br />
   </div>
</div>
<div class="main">
   <h2>B</h2>
   <div class="route">
      Z<br />
   </div>
</div>')

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

#loop through each parent node and extract the info from the children
dfs<-lapply(1:length(mainnodes), function(id){
  #assume a single title node or same number as routes
  title <- mainnodes[id] %>% html_nodes("h2") %>% html_text() %>% trimws()
  #Count the number of img nodes per parent.
  route <- mainnodes[id] %>% html_nodes("div.route") %>% html_text() %>% trimws()

  tibble(id, title, route)
})

answer<-bind_rows(dfs)
answer

# A tibble: 3 x 3
     id title route
  <int> <chr> <chr>
1     1 A     X    
2     1 A     Y    
3     2 B     Z