Вот скрипт, который собирает континенты и страны во фрейм данных.
- Итерация по
li
узлам исходного кода - Извлечение континента и страны каждого из них
li
с использованием функции helper
- Сохранение данных во фрейме данных
# Helper function
helper <- function(li)
c(continent=gsub('.*href="https://www\\.worldatlas\\.com/webimage/countrys/([A-z .]*?)/.*\\.htm".*',
'\\1', li, perl = TRUE),
country=rvest::html_text(li))
# Scrap the data
u <- 'https://www.worldatlas.com/cntycont.htm'
continents <- c('africa', 'asia', 'europe', 'namerica', 'oceania', 'samerica')
m <- t(vapply(rvest::html_nodes(xml2::read_html(u), 'li'), helper, FUN.VALUE = character(2)))
# Make a clean data frame
df <- data.frame(m)
df <- df[df$continent %in% continents,]
rownames(df) <- 1:dim(df)[[1]]
# A glimpse
head(df)
# continent country
# 1 africa Algeria
# 2 africa Angola
# 3 africa Benin
# 4 africa Botswana
# 5 africa Burkina
# 6 africa Burundi
tail(df)
# continent country
# 189 samerica Guyana
# 190 samerica Paraguay
# 191 samerica Peru
# 192 samerica Suriname
# 193 samerica Uruguay
# 194 samerica Venezuela