inst/old/download_imagens.R

require(httr)
require(rvest)
require(lubridate)
require(magrittr)
require(stringr)

baixa_sabesp_img <- function(x) {
  link <- 'http://www2.sabesp.com.br/mananciais/divulgacaopcj.aspx'
  txt <- GET(link)
  viewstate <- txt %>% content('text') %>% html %>% html_node('#__VIEWSTATE') %>% html_attr('value')
  eventval <- txt %>% content('text') %>% html %>% html_node('#__EVENTVALIDATION') %>% html_attr('value')
  data <- as.Date(x)
  dados <- list(cmbDia=day(data), 
                cmbMes=month(data), 
                cmbAno=year(data), 
                botSalvarHD.x='0', 
                botSalvarHD.y='0', 
                '__VIEWSTATE'=viewstate, 
                '__EVENTVALIDATION'=eventval)
  r <- POST(link, body=dados, cookies=unlist(txt$cookies))
  
  txt_img <- r %>% 
    content('text') %>% 
    html(encoding='UTF-8') %>% 
    html_nodes('img') %>% 
    html_attr('src') %>% last
  
  r2 <- GET(paste('http://www2.sabesp.com.br/mananciais/', txt_img ,sep='/'))
  r2 %>% content('raw') %>% writeBin(sprintf('img/%s.jpg', x))
  return(NULL)
}

datas <- sort(today() - days(0:3650))
datas %>% as.character %>% sapply(baixa_sabesp_img)
jtrecenti/sabesp documentation built on May 20, 2019, 3:17 a.m.