(以我自己的问题及其答案为基础,@astrofunkswag here)
我正在用rvest在网页上抓取网页,并使用purrr::map_df将收集到的数据转化为数据。我遇到了这样的问题:map_df只选择带有多个元素的html标记的第一个元素。理想情况下,我希望在生成的dataframe中捕获标记的所有元素,并且希望回收元素较少的标记。
请使用以下代码:
library(rvest)
library(tidyverse)
urls <- list("https://en.wikipedia.org/wiki/FC_Barcelona",
"https://en.wikipedia.org/wiki/Rome")
h <- urls %>% map(read_html)
out <- h %>% map_df(~{
a <- html_nodes(., "#firstHeading") %>% html_text()
b <- html_nodes(., ".toctext") %>% html_text()
a <- ifelse(length(a) == 0, NA, a)
b <- ifelse(length(b) == 0, NA, b)
df <- tibble(a, b)
})
out它产生以下输出:
> out
# A tibble: 2 x 2
a b
<chr> <chr>
1 FC Barcelona History
2 Rome Etymology
> 这个输出是不需要的,因为它只包含与b对应的标签的第一个元素。在源网页中,与b相关的元素是网页的字幕。所需的输出大致如下所示:
a b
<chr> <chr>
1 FC Barcelona History
2 FC Barcelona 1899–1922: Beginnings
3 FC Barcelona 1923–1957: Rivera, Republic and Civil War
.
.
6 Rome Etymology
7 Rome History
8 Rome Earliest history
.
.
> 发布于 2019-05-03 01:53:45
来自?ifelse
如果其他程序返回与测试形状相同的值。
例如,请参见
ifelse(FALSE, 20, 1:5)
#[1] 1由于length(FALSE)为1,因此只选择了1:5的第一个值,即1。
同样的,当你在做
ifelse(length(a) == 0, NA, a)length(length(a) == 0)为1,因此只返回a的第一个值。
在本例中,我们可以使用if而不是ifelse,因为我们只有一个元素要检查,因为
if(FALSE) 20 else 1:5 #returns
#[1] 1 2 3 4 5因此,它将通过以下方式给出输出
library(tidyverse)
library(rvest)
h %>% map_df(~{
a <- html_nodes(., "#firstHeading") %>% html_text()
b <- html_nodes(., ".toctext") %>% html_text()
a <- if (length(a) == 0) NA else a
b <- if (length(b) == 0) NA else b
tibble(a,b)
})
# a b
# <chr> <chr>
# 1 FC Barcelona History
# 2 FC Barcelona 1899–1922: Beginnings
# 3 FC Barcelona 1923–1957: Rivera, Republic and Civil War
# 4 FC Barcelona 1957–1978: Club de Fútbol Barcelona
# 5 FC Barcelona 1978–2000: Núñez and stabilization
# 6 FC Barcelona The Dream Team era
# 7 FC Barcelona 2000–2008: Exit Núñez, enter Laporta
# 8 FC Barcelona 2008–2012: Guardiola era
# 9 FC Barcelona 2014–present: Bartomeu era
#10 FC Barcelona Support
# … with 78 more rowshttps://stackoverflow.com/questions/55962196
复制相似问题