简体   繁体   中英

Specify download folder in RSelenium

I am using RSelenium to navigate towards a webpage which contains a button to download a file. I use RSelenium to click this button which downloads the file. However, the files are by default downloaded in my folder 'downloads', whereas I want to file to be downloaded in my working directory. I tried specifying a chrome profile as below but this did not seem to do the job:

wd <- getwd()
cprof <- getChromeProfile(wd, "Profile 1")
remDr <- remoteDriver(browserName= "chrome", extraCapabilities = cprof) 

The file is still downloaded in the folder 'downloads', rather than my working directory. How can this be solved?

The solution involves setting the appropriate chromeOptions outlined at https://sites.google.com/a/chromium.org/chromedriver/capabilities . Here is an example on a windows 10 box:

library(RSelenium)
eCaps <- list(
  chromeOptions = 
    list(prefs = list(
      "profile.default_content_settings.popups" = 0L,
      "download.prompt_for_download" = FALSE,
      "download.default_directory" = "C:/temp/chromeDL"
    )
    )
)
rD <- rsDriver(extraCapabilities = eCaps)
remDr <- rD$client
remDr$navigate("http://www.colorado.edu/conflict/peace/download/")
firstzip <- remDr$findElement("xpath", "//a[contains(@href, 'zip')]")
firstzip$clickElement()
> list.files("C:/temp/chromeDL")
[1] "peace.zip"

I've been trying the alternatives, and it seems that @Bharath's first comment about giving up on fiddling with the prefs (it doesn't seem possible to do that) and instead moving the file from the default download folder to the desired folder is the way to go. The trick to making this a portable solution is finding where the default download directory is—of course it varies by os ( which you can get like so )—and you need to find the user's username too:

desired_dir <- "~/Desktop/cool_downloads" 
file_name <- "whatever_I_downloaded.zip"

# build path to chrome's default download directory
if (Sys.info()[["sysname"]]=="Linux") {
    default_dir <- file.path("home", Sys.info()[["user"]], "Downloads")
} else {
    default_dir <- file.path("", "Users", Sys.info()[["user"]], "Downloads")
}

# move the file to the desired directory
file.rename(file.path(default_dir, file_name), file.path(desired_dir, file_name))

Look this alternative way. Your download folder should be empty.

List the files inside the folder

down.list <- list.files(path = "E:/Downloads/",all.files = T,recursive = F)

Move all files to specific folder

file.rename(from = paste0("E:/Downloads/",down.list),to = paste0("E:/1/scrape/",down.list))

It works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM