Advertisement
monchimon00

9.2.1Scraper

Apr 24th, 2024
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 6.38 KB | Source Code | 0 0
  1.  get_documents_path <- function() {
  2.     if (Sys.info()['sysname'] == 'Windows') {
  3.       command <- 'cmd.exe /c echo %USERPROFILE%\\Documents'
  4.       documents_path <- shell(command, intern = TRUE)
  5.       # Remove any trailing whitespace or newline characters
  6.       documents_path <- gsub("[\r\n]", "", documents_path)
  7.      
  8.       if (file.exists(documents_path)) {
  9.         return(documents_path)
  10.       } else {
  11.         # If Documents folder doesn't exist, try "Documentos" for Spanish systems
  12.         command_spanish <- 'cmd.exe /c echo %USERPROFILE%\\Documentos'
  13.         documents_path_spanish <- shell(command_spanish, intern = TRUE)
  14.         documents_path_spanish <- gsub("[\r\n]", "", documents_path_spanish)
  15.        
  16.         if (file.exists(documents_path_spanish)) {
  17.           return(documents_path_spanish)
  18.         } else {
  19.           return(NULL)  # Neither Documents nor Documentos folder found
  20.         }
  21.       }
  22.     } else {
  23.       return(NULL)  # For non-Windows systems
  24.     }
  25.   }
  26. Documents_path <- get_documents_path()
  27. # Tipo de Data : Chr (character)
  28. download_directory <- paste0(Documents_path, "\\Integration\\DOWNLOADS")
  29. move_directory <- paste0(Documents_path, "\\Integration\\DATA\\MODELO")
  30. library(RSelenium)
  31. library(wdman)
  32. library(netstat)
  33. library(tidyverse)
  34. library(readxl)
  35. library(openxlsx)
  36. system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
  37. # Set the download directory path
  38. download_directory <- download_directory
  39.  
  40. # Set Chrome preferences
  41. eCaps <- list(
  42.   chromeOptions =
  43.     list(prefs = list(
  44.       "download.default_directory" = download_directory
  45.     )
  46.     )
  47. )
  48. rs_driver_object <- rsDriver( browser = "chrome", chromever = "121.0.6167.85", extraCapabilities = eCaps)
  49. remDr <- rs_driver_object$client
  50. #Se accede al portal contable proporcionando el link de acceso
  51.  
  52. remDr$navigate("https://flexicredit.vortem.com/web#action=189&model=vor.cre_prestamos&view_type=kanban&cids=1&menu_id=124")
  53.  
  54. #Se pone el sistema en reposo por medio segundo para que pueda procesar lo anterior antes de recibir una nueva instruccion.
  55.  
  56. Sys.sleep(.5)
  57.  
  58. #Se maximiza el tamaño de la pestaña.
  59.  
  60. remDr$maxWindowSize()
  61.  
  62.  
  63. #findElement localiza el campo donde se coloca el usuario mediante su xpath.
  64.  
  65. username <- remDr$findElement(using = 'xpath', '//*[@id="login"]')
  66.  
  67. #sendKeysToElement coloca nombre de usuario del campo username.
  68.  
  69. username$sendKeysToElement(list("**********@flexicredit.mx"))
  70.  
  71. #Se localiza el campo donde se coloca el password mediante su xpath.
  72.  
  73. password <- remDr$findElement(using = 'xpath', '//*[@id="password"]')
  74.  
  75. #Se coloca la contraseña del campo password.
  76.  
  77. password$sendKeysToElement(list("*************"))
  78.  
  79. # Localiza boton de submit / siguiente  
  80. submit_button <- remDr$findElement(using = 'xpath', '/html/body/div[1]/main/div/form/div[3]/button')
  81.  
  82. # se hace un click sobre el elemento, para acceder con credenciales a portal web.
  83. submit_button$clickElement()
  84.  
  85. # Sistema se coloca en reposo, en espera de carga del acceso.
  86. Sys.sleep(4)
  87. Cartera_de_credito <- remDr$findElement(using = 'link text', 'Cartera de Crédito')
  88. Cartera_de_credito$clickElement()
  89.  
  90. Ver_prestamos <- remDr$findElement(using = 'link text', 'Ver Préstamos')
  91. Ver_prestamos$clickElement()
  92.  
  93. Ver_lista <- remDr$findElement(using = 'xpath', '//button[@aria-label="Ver list"]')
  94. Ver_lista$clickElement()
  95.  
  96. Sys.sleep(1)
  97.  
  98. Checkbox_todo <- remDr$findElement(using = 'xpath', '//input[@class="custom-control-input"]')
  99. Checkbox_todo$clickElement()
  100.  
  101. Seleccionar_todos <- remDr$findElement(using = 'xpath', '//a[@class="o_list_select_domain"]')
  102. Seleccionar_todos$clickElement()
  103.  
  104. Accion <- remDr$findElement(using = 'xpath', '//button[@aria-expanded="false"]')
  105. Accion$clickElement()
  106.  
  107. Accion2 <- remDr$findElement(using = 'xpath', '//button[@aria-expanded="false"]')
  108. Accion2$clickElement()
  109.  
  110. Exportar <- remDr$findElement(using = 'xpath', '//a[@role="menuitemcheckbox"]')
  111. Exportar$clickElement()
  112.  
  113. Sys.sleep(2)
  114.  
  115. Plantilla <- remDr$findElement(using = 'xpath', '//select[@class="form-control ml-4 o_exported_lists_select"]')
  116. Plantilla$clickElement()
  117.  
  118. Plantilla_BaseDeDatosModelov1<- remDr$findElement(using = 'xpath', '//option[@value="85"]')
  119. Plantilla_BaseDeDatosModelov1$clickElement()
  120.  
  121. Sys.sleep(1)
  122.  
  123. ExportarArchivo <- remDr$findElement(using = 'xpath', '//button[@class="btn btn-primary"]')
  124. ExportarArchivo$clickElement()
  125.  
  126. Sys.sleep(60)
  127. # Otro nombre para la finalidad del ejercicio, downloads_folder
  128.   downloads_folder <- download_directory
  129.  
  130. # El folder de destino es el objeto establecido como move_directory  
  131.   destination_folder <- move_directory
  132.  
  133. # La funcion list.files genera una lista de los archivos contenidos en la carpeta de downloads_folder
  134.   downloaded_files <- list.files(downloads_folder, full.names = TRUE, recursive = FALSE)
  135.  
  136. # 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.
  137.   downloaded_files <- downloaded_files[file.info(downloaded_files)$isdir == FALSE]
  138.  
  139. # El orden de los archivos se acomodan en orden temporal de fecha de creacion
  140.   downloaded_files <- downloaded_files[order(file.info(downloaded_files)$mtime, decreasing = TRUE)]
  141.   new_file_name <- "BaseDeDatosModelo.xlsx"
  142.  
  143.   # 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.
  144.  
  145.   if (length(downloaded_files) > 0) {
  146.    
  147.     # Define el archivo mas nuevo en este caso el recientemente descargado.
  148.     most_recent_file <- downloaded_files[1]
  149.    
  150.     # Define la ruta hacia la cual el archivo va a guardarse.
  151.     destination_path <- file.path(destination_folder, new_file_name)
  152.    
  153.     # Mover el archivo mas reciente al folder destino.
  154.     file.rename(most_recent_file, destination_path)
  155.     cat("Moved file:", most_recent_file, "\nTo destination:", destination_path, "\n")
  156.   } else {
  157.     cat("No files to move in the Downloads folder.\n")
  158.   }
  159.  
  160. # En la pantalla se vera un mensaje, si el archivo fue movido veremos:
  161. # "Moved file: ****.xlsx To destination: C:/Users/****"
  162. # En el caso de que no se haya movido veremos un mensaje que mencione "No files to move in the Downloads folder."
  163.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement