如何使用 RSelenium 上传文件?

How to upload files with RSelenium?

我正在尝试了解如何使用 R/RSelenium 上传文件。资讯:

我尝试了这个 SO 问题的最高评论:

How to upload file using Selenium WebDriver in Java

示例:

url <- "https://www.freepdfconvert.com/pdf-word"
path <- "C:/path_to_folder/filename.pdf"

remDr$navigate(url)

upload_btn <- remDr$findElement(using = "id", "clientUpload")
upload_btn$sendKeysToElement(path)

但我收到以下错误消息:

Selenium message:java.lang.String cannot be cast to java.util.List

Error:   Summary: UnknownError
     Detail: An unknown server-side error occurred while processing the command.
     class: java.lang.ClassCastException
     Further Details: run errorDetails method

使用的文件夹映射到虚拟机。 Autoit 是不可能的,因为它只适用于 Windows。

也试过 upload_btn$sendKeysToElement(list(path)) 没有 return 错误,但它也不起作用。

感谢任何帮助。


编辑:

我认为这应该有效,但我在查看屏幕截图时看到错误:

执行完所有这些后,此脚本不起作用。 (以约翰为例)

library(RSelenium)

remDr <- remoteDriver(remoteServerAddr = "192.168.99.100" 
                                            , port = 4445L
                                            , browserName = "chrome"
)
remDr$open()
remDr$navigate("https://gallery.shinyapps.io/uploadfile")
webElem <- remDr$findElement("id", "file1")

# create a dummy csv 
x <- data.frame(a = 1:4, b = 5:8, c = letters[1:4])
write.csv(x, file = "testcsv.csv", row.names = FALSE)

# post the file to the app
path <- "/home/docker/vm_share/testcsv.csv"
webElem$sendKeysToElement(list(path))

remDr$close()
remDr$closeServer()

截图:

sendKeysToElement 方法需要一个列表。路径需要作为列表传递:

library(RSelenium)
appURL <- "https://www.freepdfconvert.com/pdf-word"
# create sample pdf
tfile <- tempfile("sample", fileext = ".pdf")
pdf(tfile,width=7,height=5)
x=rnorm(100)
y=rnorm(100,5,1)
plot(x,lty=2,lwd=2,col="red")
lines(y,lty=3,col="green")
dev.off()

rD <- rsDriver()
remDr <- rD$client
remDr$navigate(appURL)

upload_btn <- remDr$findElement(using = "id", "clientUpload")
upload_btn$sendKeysToElement(list(tfile))

......
# cleanup when finished
rm(rD)
gc()

另请参阅 RSelenium 包本身中的演示 https://github.com/ropensci/RSelenium/blob/master/demo/selFileUpload.R and OpenFileDialog in R Selenium