R - Waiting for page to load in RSelenium with PhantomJS
Solution using while/tryCatch:
remDr$navigate("<webpage url>")webElem <-NULLwhile(is.null(webElem)){ webElem <- tryCatch({remDr$findElement(using = 'name', value = "<value>")}, error = function(e){NULL}) #loop until element with name <value> is found in <webpage url>}
To tack on a bit more convenience to Victor's great answer, a common element on tons of pages is body which can be accessed via css. I also made it a function and added a quick random sleep (always good practice). This should work without you needing to assign the element on most web pages with text:
##use double arrow to assign to global environment permanently#remDr <<- remDrwetest <- function(sleepmin,sleepmax){ remDr <- get("remDr",envir=globalenv()) webElemtest <-NULL while(is.null(webElemtest)){ webElemtest <- tryCatch({remDr$findElement(using = 'css', "body")}, error = function(e){NULL}) #loop until element with name <value> is found in <webpage url> } randsleep <- sample(seq(sleepmin, sleepmax, by = 0.001), 1) Sys.sleep(randsleep)}
Usage:
remDr$navigate("https://bbc.com/news")clickable <- remDr$findElements(using='xpath','//button[contains(@href,"")]')clickable[[1]]$clickElement()wetest(sleepmin=.5,sleepmax=1)