Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- get_documents_path <- function() {
- if (Sys.info()['sysname'] == 'Windows') {
- command <- 'cmd.exe /c echo %USERPROFILE%\\Documents'
- documents_path <- shell(command, intern = TRUE)
- # Remove any trailing whitespace or newline characters
- documents_path <- gsub("[\r\n]", "", documents_path)
- if (file.exists(documents_path)) {
- return(documents_path)
- } else {
- # If Documents folder doesn't exist, try "Documentos" for Spanish systems
- command_spanish <- 'cmd.exe /c echo %USERPROFILE%\\Documentos'
- documents_path_spanish <- shell(command_spanish, intern = TRUE)
- documents_path_spanish <- gsub("[\r\n]", "", documents_path_spanish)
- if (file.exists(documents_path_spanish)) {
- return(documents_path_spanish)
- } else {
- return(NULL) # Neither Documents nor Documentos folder found
- }
- }
- } else {
- return(NULL) # For non-Windows systems
- }
- }
- Documents_path <- get_documents_path()
- # Tipo de Data : Chr (character)
- download_directory <- paste0(Documents_path, "\\Integration\\DOWNLOADS")
- move_directory <- paste0(Documents_path, "\\Integration\\DATA\\MODELO")
- library(RSelenium)
- library(wdman)
- library(netstat)
- library(tidyverse)
- library(readxl)
- library(openxlsx)
- system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
- # Set the download directory path
- download_directory <- download_directory
- # Set Chrome preferences
- eCaps <- list(
- chromeOptions =
- list(prefs = list(
- "download.default_directory" = download_directory
- )
- )
- )
- rs_driver_object <- rsDriver( browser = "chrome", chromever = "121.0.6167.85", extraCapabilities = eCaps)
- remDr <- rs_driver_object$client
- #Se accede al portal contable proporcionando el link de acceso
- remDr$navigate("https://flexicredit.vortem.com/web#action=189&model=vor.cre_prestamos&view_type=kanban&cids=1&menu_id=124")
- #Se pone el sistema en reposo por medio segundo para que pueda procesar lo anterior antes de recibir una nueva instruccion.
- Sys.sleep(.5)
- #Se maximiza el tamaño de la pestaña.
- remDr$maxWindowSize()
- #findElement localiza el campo donde se coloca el usuario mediante su xpath.
- username <- remDr$findElement(using = 'xpath', '//*[@id="login"]')
- #sendKeysToElement coloca nombre de usuario del campo username.
- username$sendKeysToElement(list("**********@flexicredit.mx"))
- #Se localiza el campo donde se coloca el password mediante su xpath.
- password <- remDr$findElement(using = 'xpath', '//*[@id="password"]')
- #Se coloca la contraseña del campo password.
- password$sendKeysToElement(list("*************"))
- # Localiza boton de submit / siguiente
- submit_button <- remDr$findElement(using = 'xpath', '/html/body/div[1]/main/div/form/div[3]/button')
- # se hace un click sobre el elemento, para acceder con credenciales a portal web.
- submit_button$clickElement()
- # Sistema se coloca en reposo, en espera de carga del acceso.
- Sys.sleep(4)
- Cartera_de_credito <- remDr$findElement(using = 'link text', 'Cartera de Crédito')
- Cartera_de_credito$clickElement()
- Ver_prestamos <- remDr$findElement(using = 'link text', 'Ver Préstamos')
- Ver_prestamos$clickElement()
- Ver_lista <- remDr$findElement(using = 'xpath', '//button[@aria-label="Ver list"]')
- Ver_lista$clickElement()
- Sys.sleep(1)
- Checkbox_todo <- remDr$findElement(using = 'xpath', '//input[@class="custom-control-input"]')
- Checkbox_todo$clickElement()
- Seleccionar_todos <- remDr$findElement(using = 'xpath', '//a[@class="o_list_select_domain"]')
- Seleccionar_todos$clickElement()
- Accion <- remDr$findElement(using = 'xpath', '//button[@aria-expanded="false"]')
- Accion$clickElement()
- Accion2 <- remDr$findElement(using = 'xpath', '//button[@aria-expanded="false"]')
- Accion2$clickElement()
- Exportar <- remDr$findElement(using = 'xpath', '//a[@role="menuitemcheckbox"]')
- Exportar$clickElement()
- Sys.sleep(2)
- Plantilla <- remDr$findElement(using = 'xpath', '//select[@class="form-control ml-4 o_exported_lists_select"]')
- Plantilla$clickElement()
- Plantilla_BaseDeDatosModelov1<- remDr$findElement(using = 'xpath', '//option[@value="85"]')
- Plantilla_BaseDeDatosModelov1$clickElement()
- Sys.sleep(1)
- ExportarArchivo <- remDr$findElement(using = 'xpath', '//button[@class="btn btn-primary"]')
- ExportarArchivo$clickElement()
- Sys.sleep(60)
- # Otro nombre para la finalidad del ejercicio, downloads_folder
- downloads_folder <- download_directory
- # El folder de destino es el objeto establecido como move_directory
- destination_folder <- move_directory
- # La funcion list.files genera una lista de los archivos contenidos en la carpeta de downloads_folder
- downloaded_files <- list.files(downloads_folder, full.names = TRUE, recursive = FALSE)
- # La funcion funcion file.info() ofrece informacion acerca de los archivos, el tipo de informacion sera dada por el detalle $... en la funcion, en este caso excluye los archivos que sean directorios, buscamos archivos y no alguna carpeta.
- downloaded_files <- downloaded_files[file.info(downloaded_files)$isdir == FALSE]
- # El orden de los archivos se acomodan en orden temporal de fecha de creacion
- downloaded_files <- downloaded_files[order(file.info(downloaded_files)$mtime, decreasing = TRUE)]
- new_file_name <- "BaseDeDatosModelo.xlsx"
- # Lo que se hace en la funcion if sera evaluar si hubo o no hubo nuevos archivos en la carpeta de descargas, lo cual en teoria deberia ser siempre positivo, igual o mayor a 1 sin embargo para efectos de validacion se hace esta condicion.
- if (length(downloaded_files) > 0) {
- # Define el archivo mas nuevo en este caso el recientemente descargado.
- most_recent_file <- downloaded_files[1]
- # Define la ruta hacia la cual el archivo va a guardarse.
- destination_path <- file.path(destination_folder, new_file_name)
- # Mover el archivo mas reciente al folder destino.
- file.rename(most_recent_file, destination_path)
- cat("Moved file:", most_recent_file, "\nTo destination:", destination_path, "\n")
- } else {
- cat("No files to move in the Downloads folder.\n")
- }
- # En la pantalla se vera un mensaje, si el archivo fue movido veremos:
- # "Moved file: ****.xlsx To destination: C:/Users/****"
- # En el caso de que no se haya movido veremos un mensaje que mencione "No files to move in the Downloads folder."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement