Launch RSelenium Browser regardless of port open/closed

1.5k views Asked by At

Question: Is there a function that will open a selenium browser if none is already open, or close the current browser and reset the port and relaunch a browser?

Rationale: I work with big loops in RSelenium that occasionally crash, so sometimes I don't know if a port is open or browser is open in looped code. I'd like a RSelenium launcher that launches a browser regardless if one is open or if the port is in use.

Attempt: I tried this approach with tryCatch() but I still get the wdman error that a port is open if I try to launch it twice:

browserpreference <- "chrome"
tryCatch({rD <- rsDriver(port = 4444L, browser = paste0(browserpreference))}
  ,error=function(rD,remDr){
          try(remDr$close(), silent=T)
          try(rD$server$stop(),silent=T)
          try(suppressWarnings(rm(rD, envir = .GlobalEnv)), silent=T)
          try(suppressWarnings(rm(remDr, envir = .GlobalEnv)), silent=T)
          gc()
          rD <- rsDriver(port = 4444L, browser = paste0(browserpreference))
        })

If I try this twice I get this error:

Error in wdman::selenium(port = port, verbose = verbose, version = version,  : 
  Selenium server signals port = 4444 is already in use.

Thanks!

2

There are 2 answers

0
BatmanFan On

I faced this issue, it is because of a java run time left behind for each orphaned port. Killing each of these frees up the port. use the following to terminate the java run time left behind :

system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
0
Christopher Carroll Smith On

Here is a function for starting RSelenium that works regardless of whether the port is open or closed.

start_selenium <- function(attempted = 0, condition = "Success starting Selenium web driver!", browserpreference = "chrome"){
  if(attempted >= 2){
    return("Failure starting Selenium web driver: Port in use and Java task kill didn't fix it!")
  }
  tryCatch({
    .GlobalEnv$rD <- rsDriver(port = 4444L, browser = paste0(browserpreference))
    .GlobalEnv$driver <- rD[["client"]]
  }, error = function(error_condition) {
    if(grepl("already in use",error_condition, fixed = TRUE)){
      tryCatch(driver$close(),error = function(error_condition){message(error_condition)})
      rD[["server"]]$stop()
      system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
      attempted <- attempted + 1
      condition <<- start_selenium(attempted)
    }
  })
  return(condition)
}