Search code examples
rselenium-webdrivermagick

Save screenshot as variable in R Selenium


I'm trying to store a screenshot from Selenium to a variable so I can work out it's height:

library(RSelenium)
library(magick)
server <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4444,
                      browserName = "firefox")
server$open()
server$navigate("https://google.com")
screenshot <- server$screenshot(display = FALSE)
image_info(screenshot)

Error: The 'image' argument is not a magick image object.

Strangely, this works if I output server$screenshot to a file and load it back in:

server$screenshot(display = FALSE, file"/home/person/img.png")
blankPNG <-  image_read("/home/person/img.png")

I know that server$screenshot returns a "base64 encoded PNG", but how can I read it as such? print(screenshot) returns a string.


Solution

  • Finally found it:

    library('base64enc')
    
    # this returns a list of base64 characters
    screenshot <- server$screenshot(display = FALSE)
    
    # converts the base64 characters into a vector
    screenshot <- base64decode(toString(screenshot), output = NULL)
    
    # reads the vector as stores it as a PNG
    screenshot <- image_read(screenshot)