(building on my own question and its answer by @astrofunkswag here)
I am webscraping webpages with rvest
and turning the collected data into a dataframe using purrr::map_df
. I run into the problem that map_df
selects only the first element of html tags with multiple elements. Ideally, I would like all elements of a tag to be captured in the resulting dataframe, and the tags with fewer elements to be recycled.
Take the following code:
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
which produces the following output:
> out
# A tibble: 2 x 2
a b
<chr> <chr>
1 FC Barcelona History
2 Rome Etymology
>
This output is not desired, because it includes only the first element of the tags corresponding to b
. In the source webpages, the elements associated to b
are the subtitles of the webpage. The desired output looks more or less like this:
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
.
.
>