【问题标题】:rvest: handling different number of nested classesrvest:处理不同数量的嵌套类
【发布时间】:2020-07-02 14:25:15
【问题描述】:

我不知道如何描述问题,所以我将直接进入示例。
我有一个 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 中的行数不同。我也不知道如何索引类main

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

【问题讨论】:

    标签: r purrr rvest tibble


    【解决方案1】:

    这遵循与您之前的问题类似的策略。诀窍是遍历每个子节点,创建标题和路由的单独 data.frame,然后将所有单独的 dataframe 组合成最终结果。
    此解决方案确实依赖于每个节点只有 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 
    

    【讨论】:

    • 恭喜!您还可以包括索引(以防万一有两个相似的标题)?每个main 类都应该有一个唯一的索引。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多