【发布时间】: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
任何帮助将不胜感激!
【问题讨论】: