I would like to apply a loop to scrape data from multiple webpages in R. I am able to scrape the data for one webpage, however when I attempt to use a loop for multiple pages, I get a frustrating error. I have spent hours tinkering, to no avail. Any help would be greatly appreciated!!!
This works:
###########################
# GET COUNTRY DATA
###########################
library("rvest")
site <- paste("http://www.countryreports.org/country/","Norway",".htm", sep="")
site <- html(site)
stats<-
data.frame(names =site %>% html_nodes(xpath="//*/td[1]") %>% html_text() ,
facts =site %>% html_nodes(xpath="//*/td[2]") %>% html_text() ,
stringsAsFactors=FALSE)
stats$country <- "Norway"
stats$names <- gsub('[\r\n\t]', '', stats$names)
stats$facts <- gsub('[\r\n\t]', '', stats$facts)
View(stats)
However, when I attempt to write this in a loop, I receive an error
###########################
# ATTEMPT IN A LOOP
###########################
country<-c("Norway","Sweden","Finland","France","Greece","Italy","Spain")
for(i in country){
site <- paste("http://www.countryreports.org/country/",country,".htm", sep="")
site <- html(site)
stats<-
data.frame(names =site %>% html_nodes(xpath="//*/td[1]") %>% html_text() ,
facts =site %>% html_nodes(xpath="//*/td[2]") %>% html_text() ,
stringsAsFactors=FALSE)
stats$country <- country
stats$names <- gsub('[\r\n\t]', '', stats$names)
stats$facts <- gsub('[\r\n\t]', '', stats$facts)
stats<-rbind(stats,stats)
stats<-stats[!duplicated(stats),]
}
Error:
Error: length(url) == 1 is not TRUE
In addition: Warning message:
In if (grepl("^http", x)) { :
the condition has length > 1 and only the first element will be used