R/vigencia.R

#' Enrich the csv file generated by idealisto function.
#'
#' This function enriches the csv file generated by idealisto with some other variables related with the current situation of the downloaded ads. It's useful to know if the ads are still online days or weeks later or have been removed. If the ad has been removed, vigencia function will tell how many days ago and if the ad is still online it will tell if they have a new price.
#' @param ruta A valid path in your computer that leads to an idealisto created csv file.
#' @return It returns a csv file with more variables. It will be saved in the root (~/).
#' @export
vigencia <- function(ruta) {
  
  df <- read.csv(ruta)
  
  list.of.packages <- c("stringr", "rvest", "httr")
  new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
  if(length(new.packages)>0) {install.packages(new.packages)}
  
  
  library(stringr)
  library(rvest)
  library(httr)
  
  
  desktop_agents <-  c('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
                       'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
                       'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
                       'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14',
                       'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',
                       'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
                       'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
                       'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',
                       'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
                       'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0')
  
  
  
  urls <- as.character(df$Url)
  df$fecha_baja <- NA
  df$nuevo_precio <- NA
  df$cambio_precio_agrup <- NA
  df$MenosDe30 <- NA
  
  start <- Sys.time()
  start_2 <- Sys.time()
  
  for(p in 1:length(urls)) {
    
    x <- GET(urls[p], add_headers('user-agent' = desktop_agents[sample(1:10, 1)]))
    fecha_baja <- x %>% read_html() %>% html_nodes("p")
    
    if (as.character(fecha_baja[1]) == '<p class="pager-count"> </p>') {
      
      df$nuevo_precio[p] <- x %>% read_html() %>% html_nodes(".h3-simulated.txt-bold") %>% html_text()
      df$nuevo_precio[p] <- as.integer(str_replace_all(string = df$nuevo_precio[p], pattern = " eur/mes|\\.", replacement = ""))
      print(paste("Sigue dado de alta con este precio:", df$nuevo_precio[p], "€."))
      
    } else if (isTRUE(str_detect(fecha_baja[1], "Esto puede haber ocurrido porque"))) {
      df$fecha_baja[p] <- "fecha_baja sin fecha"
      print(df$fecha_baja[p])
    } else {
      df$fecha_baja[p] <- str_replace_all(fecha_baja[1], "<p>|</p>", "")
      print(df$fecha_baja[p])
    }
    
    if (Sys.time() > start_2 + 420) {
      stop_t <- sample(x = 100:120, size = 1)
      print(paste("Para que no se nos cabree Idealista vamos a parar la máquina durante", stop_t, "segundos."))
      Sys.sleep(time = stop_t)
      start_2 <- Sys.time()
    }
    Sys.sleep(sample(x = 0.5:1.2, size = 1))
  }
  
  
  
  
  df$nuevo_precio <- as.integer(df$nuevo_precio)
  df$cambio_precio <- df$Precio - df$nuevo_precio
  
  df$fecha_baja <- str_replace_all(string = str_replace_all(string = df$fecha_baja, pattern = "El anunciante lo dio de fecha_baja el ", replacement = ""), pattern =  "lunes |martes |miércoles |jueves |viernes |sábado |domingo ", replacement = "")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "fecha_baja \\(sin fecha\\)", replacement = "1 de marzo de 2018")
  
  df$fecha_baja[df$fecha_baja == "Todos los anuncios pasan el control de calidad en un tiempo aproximado de un día laborable "] <- NA
  
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = " de ", replacement = "")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "enero", replacement = "-01-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "febrero", replacement = "-02-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "marzo", replacement = "-03-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "abril", replacement = "-04-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "mayo", replacement = "-05-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "junio", replacement = "-06-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "julio", replacement = "-07-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "agosto", replacement = "-08-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "septiembre", replacement = "-09-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "octubre", replacement = "-10-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "noviembre", replacement = "-11-")
  df$fecha_baja <- str_replace_all(string = df$fecha_baja, pattern = "diciembre", replacement = "-12-")
  
  df$fecha_baja <- as.Date(df$fecha_baja, format = "%d-%m-%Y")
  
  df$vigencia <- df$fecha_baja - as.Date(df$fecha)
  df$MenosDe30[df$vigencia <= 30] <- "30 días o menos" 
  df$MenosDe30[is.na(df$vigencia)] <- "Sigue de alta"
  
  df$cambio_precio <- df$nuevo_precio - df$Precio
  df$cambio_precio_agrup[df$cambio_precio == 0] <- "Igual" 
  
  df$cambio_precio_agrup[df$cambio_precio < 0 & df$cambio_precio >= -150] <- "Rebaja de 150€ o menos" 
  df$cambio_precio_agrup[df$cambio_precio < -150 & df$cambio_precio >= -350] <- "Rebaja de entre 151€ y 350€" 
  df$cambio_precio_agrup[df$cambio_precio < -350 & df$cambio_precio >= -500] <- "Rebaja de entre 351€ y 500€" 
  df$cambio_precio_agrup[df$cambio_precio < -500] <- "Rebaja de más de 500€" 
  
  df$cambio_precio_agrup[df$cambio_precio > 0 & df$cambio_precio <= 50] <- "Aumento de 50€ o menos" 
  df$cambio_precio_agrup[df$cambio_precio > 50 & df$cambio_precio <= 100] <- "Aumento de entre 51€ y 100€" 
  df$cambio_precio_agrup[df$cambio_precio > 100] <- "Aumento de más de 101€" 
  
  try(write.csv(x = df, file = paste0("~/","vigencia_",Sys.Date(),".csv")))
  
  stop <- Sys.time()
  diff <- stop - start
  print(diff)
}
meneos/idealisto documentation built on May 25, 2019, 10:30 p.m.