I'm probably not seeing something obvious, anyway I'd like to create functions to automatically extract text from an URL already handled by a remote driver. I'd like to pass as a function arguments the xpath expression and the environment into which the remote driver could be found
library(RSelenium)
url="http://stackoverflow.com/search?q=r+program"
remdir<-remoteDriver(remoteServerAddr = "localhost", port = 4444, browserName = "firefox")
remdir$open()
remdir$navigate(url)
env<-environment()
#env should be the environment in which remdir exist (remdir itself?)
#xp the xpath expression to evaluate in the form "//*"
fun.XpathExtractText<-function(xp,env)
{
cat("\ncheck if session open\n")
#look in env for an open session
if ((eval(quote(is.na(remdir$sessionid)),envir = env)))
stop("ERROR NO SESSION ID open new one")
cat("session found\n")
#accept xpath expression as is
xp <- substitute(xp)
txt<-c()
#build the call to env
cat("calling\n")
call<-paste0("remdir$findElements(using = \"xpath\",\"",as.character(xp),"\")")
tgt<-eval(as.name(call),envir = env)
cat("Target locked\n")
txt<-lapply(tgt,function(c){c$getElementText()})
return(txt)
}
A possible call of this function could be fun.XpathExtractText("//*",env)
But soon after the call build part here comes the error message:
Error in eval(expr, envir, enclos) :
object 'remdir$findElements(using = "xpath","//*")' not found
but if I execute in env directly the call extracted from the error message it will work.
tgt<-remdir$findElements(using = "xpath","//*")
I've tried to pass as environment also remdir itself as it is an environment, but that doesn't count at all, the function get stuck in the same point after the call build. What don't I know?
Not sure what exactly you are trying to do. However eval
doesn't seem the answer. You should pass the remoteDriver
object into your function:
library(RSelenium)
url="http://stackoverflow.com/search?q=r+program"
remdir<-remoteDriver(remoteServerAddr = "localhost", port = 4444, browserName = "firefox")
remdir$open()
remdir$navigate(url)
fun.XpathExtractText<-function(xp, remdir)
{
cat("\ncheck if session open\n")
#look in env for an open session
if (is.na(remdir$sessionid))
stop("ERROR NO SESSION ID open new one")
cat("session found\n")
#accept xpath expression as is
cat("calling\n")
tgt <- remdir$findElements(using = "xpath",as.character(xp))
cat("Target locked\n")
txt<-lapply(tgt,function(c){c$getElementText()})
return(txt)
}