R:使用rvest和purrr:map_df构建数据框架:如何处理不完整的输入

R:使用rvest和purrr:map_df构建数据框架:如何处理不完整的输入,r,rvest,purrr,R,Rvest,Purrr,我正在用rvest浏览网页,并使用purrr::map_df将收集的数据转换成数据帧。我遇到的问题是,并非所有网页在我指定的每个html\u节点上都有内容,map\u df会忽略这些不完整的网页。我希望map\u df包含上述网页,并在html\u节点与内容不匹配的地方编写NA。以下面的代码为例: library(rvest) library(tidyverse) urls <- list("https://en.wikipedia.org/wiki/FC_Barcelona",

我正在用
rvest
浏览网页,并使用
purrr::map_df
将收集的数据转换成数据帧。我遇到的问题是,并非所有网页在我指定的每个
html\u节点上都有内容,
map\u df
会忽略这些不完整的网页。我希望
map\u df
包含上述网页,并在
html\u节点
与内容不匹配的地方编写
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

任何帮助都将不胜感激

您只需签入
map\u df
部分即可。由于
html\u节点
不存在时返回
字符(0)
,请检查
a
b

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   
out%map\u df(~{
%html\u文本()
b%html_text()

a谢谢。这确实是一个重复的问题,尽管问题的措辞有很大的不同。我在这里发布了一个新的问题,这个问题的基础是:,如果你有任何想法的话。
> out
# A tibble: 2 x 3
  a            b      
  <chr>        <chr>  
1 FC Barcelona History
2 Rome         History
3 Curicó       NA
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