【问题标题】:R: using rvest and purrr:map_df to build a data frame: how to deal with incomplete input [duplicate]R:使用rvest和purrr:map_df构建数据框:如何处理不完整的输入[重复]
【发布时间】:2019-05-02 23:30:08
【问题描述】:

我正在使用rvest 抓取网页,并使用purrr::map_df 将收集到的数据转换为数据框。我遇到的问题是,并非所有网页在我指定的每个html_nodes 上都有内容,而map_df 忽略了这些不完整的网页。我希望map_df 包含上述网页并在html_nodes 与内容不匹配的地方写NA。取以下代码:

library(rvest)
library(tidyverse)

urls <- list("https://en.wikipedia.org/wiki/FC_Barcelona",
             "https://en.wikipedia.org/wiki/Rome", 
             "https://es.wikipedia.org/wiki/Curic%C3%B3")
h <- urls %>% map(read_html)

out <- h %>% map_df(~{
  a <- html_nodes(., "#firstHeading") %>% html_text()
  b <- html_nodes(., "#History") %>% html_text()
  df <- tibble(a, b)
})
out

这是输出:

> out
# A tibble: 2 x 2
  a            b      
  <chr>        <chr>  
1 FC Barcelona History
2 Rome         History

这里的问题是输出数据帧不包含与#History html 节点(在本例中为第三个 url)不匹配的网站的行。我想要的输出,如下所示:

> out
# A tibble: 2 x 3
  a            b      
  <chr>        <chr>  
1 FC Barcelona History
2 Rome         History
3 Curicó       NA

任何帮助将不胜感激!

【问题讨论】:

    标签: r rvest purrr


    【解决方案1】:

    您只需签入map_df 部分。由于html_nodes 在不存在时返回character(0),因此请检查ab 的长度

    out <- h %>% map_df(~{
      a <- html_nodes(., "#firstHeading") %>% html_text()
      b <- html_nodes(., "#History") %>% html_text()
    
      a <- ifelse(length(a) == 0, NA, a)
      b <- ifelse(length(b) == 0, NA, b)
    
      df <- tibble(a, b)
    })
    out
    
    # A tibble: 3 x 2
      a            b      
      <chr>        <chr>  
    1 FC Barcelona History
    2 Rome         History
    3 Curicó       NA   
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多