def verifica(self, n_files, list_file_path, list_name_urls, nome_donwload=None): # retorna uma lista de processo arquivos lista_processoArquivo = [] err_down = self.wait_download(n_files) if not err_down: # not err_down: # se o download concluiu totalmente sem nehum erro arquivo = set(os.listdir(self.path_download_prov)).difference( set(list_file_path)) # difereça de dois conjuntos file_downloaded = arquivo.pop( ) # pega o nome do arquivo que foi baixado arquivo = list(arquivo) if len(arquivo) > 1: # Tem multiplos donwloads for i in range(0, len(arquivo), 1): nome = Tools.convert_base(str(datetime.now())) list_name_urls.append((nome, arquivo[i])) nome = nome + '.' + arquivo[i].split('.')[-1] lista_processoArquivo.append( ProcessoArquivoModel(pra_nome=nome, pra_descricao=arquivo[i], pra_erro=0)) print("multiplos") self.log_error.insert_log( "Multiplos donwloads processo, verificar!!") nome = Tools.convert_base(str( datetime.now())) if nome_donwload == None else nome_donwload list_name_urls.append( (nome, file_downloaded) ) # Primeiro é o nome que quer renomear segundo o original, o primeiro não tem extensão nome = nome + '.' + file_downloaded.split('.')[-1] lista_processoArquivo.append( ProcessoArquivoModel(pra_nome=nome, pra_descricao=file_downloaded, pra_erro=0)) return True, lista_processoArquivo else: return False, [ProcessoArquivoModel(pra_erro=1)]
def verifica(self, n_files, list_file_path, list_name_urls, nome_donwload=None): err_down = self.wait_download(n_files) if not err_down: # not err_down: # se o download concluiu totalmente sem nehum erro # print('dentro if') arquivo = set(os.listdir(self.path_download_prov)).difference(set(list_file_path)) # difereça de dois conjunts # print('hduahdushadhsuadushauhdusauhduau') file_downloaded = arquivo.pop() # pega o nome do arquivo que foi baixado arquivo = list(arquivo) if len(arquivo) > 1: # Tem multiplos donwloads for i in range(0, len(arquivo), 1): nome = Tools.convert_base(str(datetime.now())) # nome = nome + '.' + arquivo[i].split('.')[-1] print("Nome multiplos->", nome) list_name_urls.append((nome, arquivo[i])) print("multiplos") self.log_error.insert_log("Multiplos donwloads processo, verificar!!") print('Nome donload: ', file_downloaded, " Paramentro:", nome_donwload) nome = Tools.convert_base(str(datetime.now()))# if nome_donwload == None else nome_donwload list_name_urls.append((nome,file_downloaded)) # Primeiro é o nome que quer renomear segundo o original, o primeiro não tem extensão # ext = file_downloaded.split('.')[-1].lower() nome = nome + '.' + file_downloaded.split('.')[-1] # print("Nome donload :", nome, "File: ", file_downloaded) # desc_file = file_downloaded.replace("." + ext, '') # self.dicionario_acompanhamento[numero_acompanhamento].append(file_downloaded) # ADICIONANDO O NOME DO DONWLOAD, IDEPENDENTE SE TERMINOU DE BAIXAR OU NAO return True, ProcessoArquivoModel(pra_nome=nome, pra_descricao=file_downloaded,pra_erro=0) else: return False, ProcessoArquivoModel(pra_erro=1)
def fazer_donwload(self,linha,list_name_url,list_file_name): list_name_urls_aux = [] links_midia = None botao_donwload = self.pegar_linha(linha) # Pegar a linha que tem o donwload nome_arquivos = os.listdir(self.path_download_prov) # Pegar a quantidade de arquivos antes do download botao_donwload = botao_donwload.find_elements_by_tag_name('a') # é onde fica armazenado o link de donwload link = botao_donwload[0].get_attribute('href') # Pegar o link de donwload midia = str(botao_donwload[0].get_attribute('class')) # Pegar o nome da classe para ver se e audio ou video if '#liberarAutoPorSenha' in link: # Documento em sigilo print("ARQUIVO EM SIGILO") nome = "ArquvioErro"+ str(time.time()) lista_processoArquivo = [] lista_processoArquivo.append(ProcessoArquivoModel(pra_nome=nome, pra_descricao="DOCUMENTO EM SIGILO"+str(time.time()), pra_erro=2)) list_file_name +=lista_processoArquivo return if not 'linkMidiaMov' in midia: self.browser.execute_script('''window.open("{}","_blank");'''.format(link)) # Abrir nova aba self.browser.switch_to_window(self.browser.window_handles[-1])# Selecionar a aba de download WebDriverWait(self.browser, 5).until(EC.presence_of_element_located((By.TAG_NAME, 'body'))) # Esperar a página recaregar if self.verificar_se_deu_erro_pagina_donwload(): raise self.clilcar_para_baixar() self.browser.close() # fechar a guia de donwload que foi aberta self.browser.switch_to_window(self.browser.window_handles[0]) # Voltar para a primeira status, processoAqruivo = self.verifica(len(nome_arquivos), nome_arquivos, list_name_urls_aux) list_name_url += list_name_urls_aux list_file_name += processoAqruivo else: # Chegou aqui é audio ou vídeo for donw_midia in botao_donwload: nome_arquivos = os.listdir(self.path_download_prov) # Pegar a quantidade de arquivos antes do download link = donw_midia.get_attribute('href') # Pegar o link do donwload self.browser.execute_script('''window.open("{}","_blank");'''.format(link)) # Abrir nova aba # colocar em uma fução status, processoAqruivo = self.verifica(len(nome_arquivos), nome_arquivos, list_name_urls_aux) list_name_url += list_name_urls_aux list_file_name += processoAqruivo
def fazer_donwload(self,id,list_name_urls,list_file_name, obs): #n_files, list_file_path, list_name_urls, nome_donwload=None wait = WebDriverWait(self.browser,12) list_name_urls_aux = [] list_file_name_aux = [] obs_aux = "" # Varivável para verificar se é segredo de justiça tabela = self.browser.find_element_by_id(id) # Pega a tabela inteira wait.until(EC.presence_of_all_elements_located((By.XPATH,'//*[@id="{}"]/table/tbody/tr'.format(id) ))) # Esperar os elementos da tabela aparecer tabela = self.browser.find_elements_by_xpath('//*[@id="{}"]/table/tbody/tr'.format(id)) # Pegar as linhas da nova tabela de downloads for linha in tabela: # Passar pelas linhas da tabela, fazendo os donwloads, # O botão para clilcar no donwload está na td[5] # Se o nome do download for "Restrição na Visualização" não da para baixar nome_donwload_plat = linha.find_element_by_xpath('td[5]') valido = nome_donwload_plat.find_elements_by_tag_name('strike') if not('Restrição na Visualização' in str(nome_donwload_plat.text)) and len(valido)==0: # Se puder baixar o download nome_arquivos = os.listdir(self.path_download_prov) # Pegar a quantidade de arquivos antes do download link = linha.find_element_by_xpath('td[5]/a').get_attribute('href') # Link do donwload self.browser.execute_script('''window.open("{}","_blank");'''.format(link)) # Abrir nova aba, e ela faz donwload automaticamente #linha.find_element_by_xpath('td[5]/a').click() nome_donwload = link.split('=')[-1] # Pegar o id do arquivo que está no final da url # wait.until(EC.number_of_windows_to_be(1)) # Quando clicla para fazer o donwload abre mais uma aba, esperar ela fechar status,processoAqruivo = self.verifica(len(nome_arquivos), nome_arquivos,list_name_urls_aux, nome_donwload) list_file_name_aux.append(processoAqruivo) # Todos os donwloads estarão aqui else: # Se echou aqui o documento não pode ser visualizado list_file_name_aux.append(ProcessoArquivoModel(pra_erro=3,pra_nome="Erro")) obs_aux = " - Movimentação possui arquivos mas há Restrição na Visualização" print("DOCUMENTO SIGILOSO - RESTRIÇÃO NA VISUALIZAÇÃO") list_name_urls += list_name_urls_aux list_file_name += list_file_name_aux obs += obs_aux
def baixar_anexos(self, i, list_name_urls, list_file_name, els, t, acp_pra_status, list_file_path, prc_id, n_event, js): # BAIXA OS ANEXOS E CRIA ACOMPANHAMENTO ASSOCIANDO OS ANEXOS CONTIDOS NELES xpath_aux_docs = '//*[@id="TabelaArquivos"]/tbody/tr[{}]/'.format(i + 1) # PEGA A LINHA QUE TA OS DOWNLOAD xpath_aux_docs += 'td/ul/li' wait = WebDriverWait(self.browser, 10) try: wait.until( EC.presence_of_element_located((By.XPATH, xpath_aux_docs))) except: pass ul_files = self.browser.find_elements_by_xpath(xpath_aux_docs) if len(ul_files) > 0: ul_files[0].location_once_scrolled_into_view ul_files = self.browser.find_elements_by_xpath(xpath_aux_docs) j = 0 for li in ul_files: j += 1 direct = 0 n_files = len(os.listdir(self.path_download_prov)) # COLETA ARQUIVO PARA DOWLOAD li_els = li.find_elements_by_xpath('div[2]/div[1]/a') # SALVA OS ARQUIVOS if len(els) == 0: self.browser.execute_script(js[1]) sleep(1) self.browser.execute_script(js[1]) li_els = li.find_elements_by_xpath('div[2]/div[1]/a') # CAPTURA OS DOCUMENTOS doc_els = li.find_elements_by_xpath('div[1]/span') # VERIFICA SE TEM DOC PRA PEGAR if len(doc_els) > 0: # VERIFICA SE O DOWNLOAD TA BLOQUEADO if 'Bloqueado' in doc_els[0].text: continue # PEGA O TITULO DO ARQUIVO title = li_els[0].get_attribute('title').lower() # VERIFICA SE TEM PDF PARA DOWNLOAD pdf = li.find_elements_by_xpath('div[4]/div/a') if '.wav' in title: arq = open('ProcessoContemAudio.txt', 'r') string = arq.read() arq.close() arq = open('ProcessoContemAudio.txt', 'w') string += '\n' n_process = self.browser.find_element_by_xpath( '/html/body/div[2]/form/div[1]/fieldset/span[1]').text string += n_process arq.write(string) arq.close() if not self.check_file_session(): print("erro o check_file_session") return False if '.mp3' in title or len(pdf) == 0: if '.html' in title: li_els[0].click() arq = title.split('.html') direct = 1 self.donwloadAcompanhamento(arq[0]) else: # document.createElement('div'); self.browser.execute_script( 'arguments[0].setAttribute("download", "");', li_els[0]) li_els[0].click() else: pdf[0].click() try: alert = self.browser.switchTo().alert() alert.accept() except: pass t += 1 try: wait = WebDriverWait(self.browser, 2) wait.until(EC.number_of_windows_to_be(2)) wait = WebDriverWait(self.browser, 20) wait.until(EC.number_of_windows_to_be(1)) except TimeoutException: if len(self.browser.window_handles) > 1: self.browser.switch_to_window( self.browser.window_handles[1]) time.sleep(4) erro = self.browser.find_elements_by_class_name( 'texto_erro') if len(erro) > 0 and 'Sem Permis' in erro[0].text: self.browser.close() self.browser.switch_to_window( self.browser.window_handles[0]) return False tipe_err_down = -1 err_down = self.wait_download(n_files) if not direct else 0 acp_pra_status = acp_pra_status and (not err_down) xpath_dowload_arquivo = xpath_aux_docs + '[{}]/div[2]/div[1]/a' xpath_dowload_arquivo = xpath_dowload_arquivo.format(j) wait = WebDriverWait(self.browser, 10) wait.until( EC.element_to_be_clickable((By.XPATH, xpath_dowload_arquivo))) desc_file = self.browser.find_element_by_xpath( xpath_dowload_arquivo).text nome = Tools.convert_base(str(datetime.now())) if not err_down: for arq in os.listdir(self.path_download_prov): if arq not in list_file_path: list_file_path.append(arq) file_downloaded = arq break list_name_urls.append((nome, file_downloaded)) ext = file_downloaded.split('.')[-1].lower() nome = nome + '.' + ext print('.', end='') else: print(':', end='') print('title:' + title) print('erro download') erro = err_down if tipe_err_down is None else False list_file_name.append( ProcessoArquivoModel(pra_prc_id=prc_id, pra_nome=nome, pra_descricao=desc_file, pra_erro=erro)) # VERIFICA SE A SESSÃO FOI ENCERRADA if len(self.browser.window_handles) > 1: self.browser.switch_to_window(self.browser.window_handles[1]) self.browser.close() self.browser.switch_to_window(self.browser.window_handles[0]) acp_pra_status = False print(']', end='') return True
def acomp_down_aud(self, prc_id, ult_mov, bool_2_grau_numero, full=None): print('ult_mov', ult_mov) file_downloaded = None list_name_urls = [] list_audiences = [] list_file_path = [] list_acomp_download = [] not_refresh = 0 err = False acp_pra_status = None primeiro_d = True t = 0 k = 0 # PERCORRE A TABELA E FAZ O DOWNLOAD REFERENTE A CADA ACOMPANHAMENTO try: # COLETA DE DADOS PARA CRIAÇÃO DOS ACOMPANHAMENTOS E DOWNLOAD DOS ARQUIVOS wait = WebDriverWait(self.browser, 15) wait.until( EC.visibility_of_element_located(( By.XPATH, '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[1]/div' ))) acompanhamentos = self.browser.find_elements_by_xpath( '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[1]/div' ) #print('len(acompanhamentos)',len(acompanhamentos)) sleep(1) for i in range(len(acompanhamentos)): xpath_aux_data = '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/' \ 'historicoprocesso/div/div[1]/div[{}]/div[1]/span[2]/span'.format(i + 1) wait = WebDriverWait(self.browser, 15) wait.until( EC.visibility_of_element_located( (By.XPATH, xpath_aux_data))) aux_data = self.browser.find_element_by_xpath(xpath_aux_data) coordinates = aux_data.location_once_scrolled_into_view coordinates['x'] += 200 coordinates['y'] += 200 # print(coordinates) # input() self.browser.execute_script('window.scrollTo({}, {});'.format( coordinates['x'], coordinates['y'])) print(i) aux_data = self.browser.find_element_by_xpath( xpath_aux_data).text[:-1] print("data->", aux_data) aux_data = Tools.treat_date(aux_data) if ult_mov is not None: not_refresh += 1 if aux_data <= ult_mov: break k += 1 desc_process = acompanhamentos[i].find_element_by_xpath( 'div[2]').text desc_process = Tools.remove_accents(desc_process) barralugar = acompanhamentos[i].find_element_by_xpath( 'div[2]').location_once_scrolled_into_view lugar_n_event = acompanhamentos[i].find_element_by_xpath( 'div[1]/span[1]').location_once_scrolled_into_view self.browser.execute_script('window.scrollTo({}, {});'.format( lugar_n_event['x'] + 200, lugar_n_event['y'] + 200)) n_event = acompanhamentos[i].find_element_by_xpath( 'div[1]/span[1]').text[1:] # print(n_event) # input('acp_numero') # REALIZA O DOWNLOAD DOS ANEXOS DE CADA ACOMPANHAMENTO acess_donwload = acompanhamentos[i].find_element_by_xpath( 'div[3]/a') list_file_name = [] if acess_donwload.text: try: coordinate = acess_donwload.location_once_scrolled_into_view self.browser.execute_script( 'window.scrollTo({}, {});'.format( coordinate['x'], coordinate['y'])) acess_donwload.click() wait = WebDriverWait(self.browser, 5) wait.until( EC.visibility_of_element_located( (By.CLASS_NAME, 'modal-open'))) indentificador = 1 wait = WebDriverWait(self.browser, 5) wait.until( EC.element_to_be_clickable(( By.XPATH, '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[2]/div/div/div[2]/div[1]' ))) list_file = self.browser.find_elements_by_xpath( '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[2]/div/div/div[2]/div[1]/div/div' ) # input('kaio inicio') # ANEXO SUPRIMIDO files_supri = self.browser.find_elements_by_xpath( '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[2]/div/div/div[2]/div[1]/p/span' ) if len(files_supri): files_supri = int(files_supri[0].text) for i in range(files_supri): list_file_name.append( ProcessoArquivoModel( pra_prc_id=prc_id, pra_nome=Tools.convert_base( str(datetime.now())), pra_erro=3)) # input('kaio fim') for file in list_file: try: n_files = len( os.listdir(self.path_download_prov)) coordinates = file.location_once_scrolled_into_view if list_file.index(file) > 2: self.browser.execute_script( 'window.scrollTo({}, {});'.format( coordinates['x'], coordinates['y'])) try: # tempo alto por causa do dowload dos audio wait = WebDriverWait(self.browser, 25) wait.until( EC.element_to_be_clickable(( By.XPATH, '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[2]/div/div/div[2]/div[1]/div/div[{}]/a' .format(indentificador)))) file.find_element_by_xpath('a').click() wait = WebDriverWait(self.browser, 25) xpath = self.browser.find_element_by_xpath( '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[2]/div/div/div[2]/div[1]/div/div[{}]/a/div/p' .format(indentificador)) # print(xpath.text) # input("Certo?") # IF PARA VERIFICAR SE É AUDIO, AUDIO NAO É NECESSARIO REALIZAR O CLICK DEBAIXO.... if 'INTERESSADO' not in xpath.text: wait.until( EC.element_to_be_clickable(( By.XPATH, '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[2]/div/div/div[1]/a' ))) self.browser.find_element_by_xpath( '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/historicoprocesso/div/div[2]/div/div/div[1]/a' ).click() except: input('erro xpath unfunding') raise t += 1 err_down = self.wait_download(n_files) print('', end='*', flush=True) nome = Tools.convert_base(str(datetime.now())) desc_file = file.text if not err_down: for arq in os.listdir( self.path_download_prov): if arq not in list_file_path: list_file_path.append(arq) file_downloaded = arq break list_name_urls.append( (nome, file_downloaded)) # print((nome, file_downloaded)) ext = file_downloaded.split( '.')[-1].lower() nome = nome + '.' + ext acp_pra_status = True and acp_pra_status list_file_name.append( ProcessoArquivoModel( pra_prc_id=prc_id, pra_nome=nome, pra_descricao=desc_file, pra_erro=int(err_down))) except Exception as e: # input(e) raise self.log_error.insert_log( 'Download do arquivo: evento {}!'.format( n_event)) self.browser.execute_script( 'return document.readyState') acp_pra_status = False indentificador += 1 x_path_button = '/html/body/div[3]/section/div/div[2]/detalhesprocesso/partial/div/div/div[3]' \ '/historicoprocesso/div/div[2]/div/div/div[1]/button' t_ini = time.time() flag = True while flag: flag = (time.time() - t_ini) < 15 try: wait = WebDriverWait(self.browser, 5) wait.until( EC.visibility_of_element_located( (By.XPATH, x_path_button))) button_close = self.browser.find_element_by_xpath( x_path_button) button_close.click() except: pass if flag: raise except Exception as e: # input(e) raise self.log_error.insert_log( 'Download na coleta dos arquivoa: evento {}!'. format(n_event)) acp_pra_status = False self.browser.execute_script('window.scrollTo({}, {});'.format( barralugar['x'], barralugar['y'])) list_desc_proc = desc_process.split('\n') if len(list_desc_proc) == 1: list_desc_proc.append('') list_acomp_download.append([ AcompanhamentoModel(acp_tipo=list_desc_proc[0], acp_esp=list_desc_proc[1], acp_data_cadastro=aux_data, acp_prc_id=prc_id, acp_pra_status=acp_pra_status, acp_numero=n_event), list_file_name ]) # for i in list_acomp_download[-1][0].__dict__.items(): # if i[1] is not None: # print('{} \t:\t {}'.format(i[0],i[1])) # a=input('\n\npode continuar\n\n') # input('audiencias inicio') # BUSCA AS AUDIÊNCIAS PARTE 1 if (desc_process.find('Audi') == 0): # input(desc_process + '<<<<\n') aux = desc_process.split('\n') # print('kaioooooo') # input(aux) aux[1] = aux[1] if len(aux[1]) > 7 else aux[0] status, tipo = self.tratar_status_tipo(aux[0], aux[1]) data = aux[0].split('. ')[-1] data = Tools.treat_date(data) # print('\n' + tipo + '-' + status + '-' + str(data) + '-' + desc_process + '-' + str(aux_data)) # input('stop') list_audiences.append( (tipo, status, data, desc_process, aux_data)) # PEGA AS AUDIÊNCIAS APÓS ULTIMA DATA DE MOVIMENTAÇÃO DOS ACOMPANHAMENTOS for j in range(k, len(acompanhamentos)): desc_process = acompanhamentos[j].find_element_by_xpath( 'div[2]').text desc_process = Tools.remove_accents(desc_process) if "AUDIENCIA" not in desc_process[:12]: continue xpath_aux_data = '//*[@id="main-content"]/div/div[2]/detalhesprocesso/partial/div/div/div[3]/'\ 'historicoprocesso/div/div[1]/div[{}]/div[1]/span[2]/span'.format(j + 1) wait = WebDriverWait(self.browser, 10) aux_data = wait.until( EC.visibility_of_element_located( (By.XPATH, xpath_aux_data))) aux = desc_process.split('\n') status, tipo = self.tratar_status_tipo(aux[0], aux[1]) data = aux[0].split('.')[-1] # print('data->',data) data = Tools.treat_date(data) list_audiences.append( (tipo, status, data, desc_process, aux_data)) except: # raise list_acomp_download.clear() list_name_urls.clear() list_audiences.clear() self.log_error.insert_log( 'coleta de dados dos acompanhamentos do processo!'.upper()) err = True # input('\n\npode 4 continuar\n\n') raise # TRATA AS AUDIÊNCIAS list_audiences = self.trata_as_audiencias(list_audiences, prc_id) # input('audiencia tratada') return list_audiences, list_acomp_download, list_name_urls, None, err, not_refresh
def acp_aud_arq(self, acompanhamentos, j_flag, tam_acompanhamentos, dict_acp_arq_ant, data_atual, data_update, prc_id, novo_acp): list_aud = [] list_acp_arq = [] j_finali = 0 list_name_urls = [] prc_penhora = False try: for j in range(j_flag, tam_acompanhamentos): j_finali = j data = acompanhamentos[j].find_element_by_xpath('td[6]').text data_evento = Tools.treat_date(data) if data else None if novo_acp and ( (data_evento is not None) and (data_update is not None) and data_evento <= data_update): return list_acp_arq, list_aud, j_finali, list_name_urls, prc_penhora, False cadastro = acompanhamentos[j].find_element_by_xpath('td[13]').text data_cadastro = Tools.treat_date(cadastro) if cadastro else None tipo = acompanhamentos[j].find_element_by_xpath('td[9]').text tipo = Tools.remove_accents(tipo).upper() esp_tipo = acompanhamentos[j].find_element_by_xpath('td[10]').text esp_tipo = Tools.remove_accents(esp_tipo).upper() prc_penhora = prc_penhora or 'GARANTIA JUDICIAL' in tipo or 'PENHORA ON LINE' in tipo key_dict_acp_arq_ant = (data_cadastro, tipo, esp_tipo) if (data_cadastro, tipo, esp_tipo) in dict_acp_arq_ant.keys() else None aux_acomp_list = dict_acp_arq_ant.pop( key_dict_acp_arq_ant) if not novo_acp and key_dict_acp_arq_ant is not None else [[], []] aux_acomp, arq_list = aux_acomp_list[0], aux_acomp_list[1] altera_acp = False if not novo_acp and key_dict_acp_arq_ant is None: # print(2.1) continue acomp = AcompanhamentoModel( acp_id=aux_acomp[0], acp_plp_id=aux_acomp[1], acp_tipo=aux_acomp[2], acp_esp=aux_acomp[3], acp_data_cumprimento=aux_acomp[4], acp_data_evento=aux_acomp[5], acp_data_prazo=aux_acomp[6], acp_data_cadastro=aux_acomp[7], acp_data=aux_acomp[8], acp_pra_status=aux_acomp[9], acp_prc_id=prc_id, acp_numero=aux_acomp[10] ) if not novo_acp else AcompanhamentoModel(acp_prc_id=prc_id) list_arq = [] try: comentarios = acompanhamentos[j].find_elements_by_xpath( 'td[1]/table/tbody/tr/td/label/input') except: comentarios = [] if novo_acp or acomp.acp_tipo != tipo: acomp.acp_tipo = tipo altera_acp = altera_acp or True if acomp.acp_data_evento != data_evento or novo_acp: acomp.acp_data_evento = data_evento altera_acp = altera_acp or True if novo_acp or acomp.acp_esp != esp_tipo: acomp.acp_esp = esp_tipo altera_acp = altera_acp or True prazo = acompanhamentos[j].find_element_by_xpath('td[11]').text data_prazo = Tools.treat_date(prazo) if prazo else None if novo_acp or acomp.acp_data_prazo != data_prazo: acomp.acp_data_prazo = data_prazo altera_acp = altera_acp or True cumprimento = acompanhamentos[j].find_element_by_xpath('td[12]').text data_cumprimento = Tools.treat_date(cumprimento) if cumprimento else None if novo_acp or acomp.acp_data_cumprimento != data_cumprimento: acomp.acp_data_cumprimento = data_cumprimento altera_acp = altera_acp or True if novo_acp or acomp.acp_data_cadastro != data_cadastro: acomp.acp_data_cadastro = data_cadastro altera_acp = altera_acp or True # COLETA E TRATAMENDO DAS AUDIENCIAS if tipo == 'AUDIENCIA' and novo_acp: aux_aud = AudienciaModel(aud_prc_id=prc_id) aux_aud.aud_tipo = esp_tipo aud_data = acompanhamentos[j].find_element_by_xpath('td[8]').text aud_data = aud_data if aud_data else prazo aux_aud.aud_data = Tools.treat_date(aud_data) if aud_data else None aux_aud.aud_status = "DESIGNADA" if (aux_aud.aud_data is None) or (data_atual is None) or ( aux_aud.aud_data >= data_atual) else "REALIZADA" list_aud.append(aux_aud) # COLETA E TRATAMENDO DOS DOWNLOADS acp_pra_status = None if tipo in ' APURACAO ' and (esp_tipo in ['EMISSAO 2A VIA DE FATURA', 'CONTRATO'] or 'RESGATE DE GRAVACAO'.upper() in esp_tipo): if len(comentarios): comentarios[0].click() comentarios = True wait = WebDriverWait(self.browser, 5) wait.until(EC.presence_of_element_located( (By.XPATH, '//*[@id="fAcompanhamento:dtbOcorrencia"]/tbody/tr'))) acompanhamentos = self.browser.find_elements_by_xpath( '//*[@id="fAcompanhamento:dtbOcorrencia"]/tbody/tr') try: wait = WebDriverWait(self.browser, 10) wait.until(EC.presence_of_element_located((By.XPATH, 'html/body[2]/form[2]'))) except: self.browser.refresh() else: comentarios = False if comentarios: comentarios = self.browser.find_elements_by_xpath( '//*[@id="fAcompanhamento:dtbComentario:tbody_element"]/tr') comentarios.reverse() for k in comentarios: a = k.find_elements_by_xpath('td[7]/a') if len(a): a[0].click() wait = WebDriverWait(self.browser, 5) wait.until(EC.presence_of_element_located((By.ID, 'popupFrameContainer'))) self.browser.switch_to.frame( self.browser.find_element_by_css_selector( "iframe[name='__jeniaPopupFrameTarget']")) tr = self.browser.find_elements_by_xpath( '//*[@id="fAnexo:dtbAnexos:tbody_element"]/tr') acp_pra_status = True if len(tr) else False try: for l in tr: tp = l.find_element_by_xpath('td/a').text.split('.') tp_aux = True for i in arq_list: if tp[0] in i: # print('\n\n', tp[0], '<>', i) tp_aux = False break aux = False tp[-1]= tp[-1].replace(' ','').replace('\n','').replace('\t','') if (tp[-1].lower() in ['pdf', 'jpg', 'jpeg', 'mp3','wma', 'zip', 'rar', 'gif', 'xlsx','msg'] and (novo_acp or tp_aux))\ or ('RESGATE DE GRAVACAO'.upper() in esp_tipo and tp[-1].lower() not in ['docx','png'] and (novo_acp or tp_aux)): list_file_path = [_ for _ in os.listdir(self.path_download_prov)] arq_list.append(tp) try: n_files = len(os.listdir(self.path_download_prov)) + 1 l.find_element_by_xpath('td/a').click() err = self.wait_download(n_files, self.browser) if not err: try: desc_file = l.find_element_by_xpath('td/a').text except: desc_file = None file_downloaded = str() for arq in os.listdir(self.path_download_prov) : if arq not in list_file_path : list_file_path.append(arq) file_downloaded = arq break nome = Tools.convert_base(str(datetime.now())) list_name_urls.append((nome, file_downloaded)) ext = file_downloaded.split('.')[-1] nome = nome + '.' + ext list_arq.append( ProcessoArquivoModel(pra_prc_id=prc_id, pra_nome=nome, pra_acp_id=acomp.acp_id, pra_descricao=desc_file)) else: self.log_error.insert_log( 'Download do arquivo: evento de data{}!'.format( data_cadastro)) aux = True except: self.log_error.insert_log( 'Download do arquivo: evento de data {}!'.format(data_cadastro)) # raise acp_pra_status = acp_pra_status and aux except: self.log_error.insert_log('Erro-ACOMPANHAMENTOS-DOWNLOADS') # raise wait = WebDriverWait(self.browser, 5) self.browser.switch_to.default_content() wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="popupFrameContainer"]/tbody/tr[1]/td/table/tbody/tr/td[2]/img'))) self.browser.find_element_by_xpath( '//*[@id="popupFrameContainer"]/tbody/tr[1]/td/table/tbody/tr/td[2]/img').click() try: wait = WebDriverWait(self.browser, 10) wait.until(EC.presence_of_element_located((By.XPATH, 'html/body[2]/form[2]'))) except: self.browser.refresh() if acomp.acp_pra_status != acp_pra_status: acomp.acp_pra_status = acp_pra_status altera_acp = altera_acp or True if altera_acp or len(list_arq): # if not novo_acp and len(list_arq): print('altera_acp->', acomp.__dict__, '\n\n') list_acp_arq.append((acomp, list_arq)) except: self.log_error.insert_log( 'NA COLETA DOS ACOMPANHAMENTOS, ARQUIVOS E AUDIENCIAS {}'.format('NOVOS' if novo_acp else "ANTIGOS")) return [], [], -1, [], False, novo_acp # print(list_name_urls) return list_acp_arq, list_aud, j_finali, list_name_urls, prc_penhora, novo_acp
def acomp_down_aud(self, prc_id, ult_mov,bool_2_grau_numero,full = False): print("#####################PEGANDO ANDAMENTOS/AUDIENCIA#####################\n ", end='') list_acomp_download = [] list_audiences = [] list_name_urls = [] not_refresh = 0 bool_2_grau = bool_2_grau_numero err = False k = 0 # COLETA DE DADOS PARA CRIAÇÃO DOS ACOMPANHAMENTOS E DOWNLOAD DOS ARQUIVOS self.ir_para_movimentacoes() # Ir para as movimentações, e esperar elas aparecerem tam = self.tamanho_das_movimentacoes() # Pega o tamanho total das movimentações i = 0 qtd_erro = 0 while i <tam: try: k += 1 # Contar quantas vezes ele passou no for, os arquivos tem um id que é divArquivosMovimentacaoProcessomovimentacoes + o número da div, que é o k print(' {}'.format(i), end='') self.aceita_renovar_sessao() # As vezes aparece o alert para renovar a sessão, aceita-ló quando aparecer linha = self.pegar_linha_movimentacao(i) # Pega a linha inteira da movimentação n_event,aux_data,desc_process,download = self.buscar_dados(linha) # Pegar os dados já tratada, n_event - >td[2], desc_process -> td[4], aux_data->td[3] if (ult_mov is not None and (aux_data <= ult_mov)) and (not full): # Verifica se é para pegar a movimentação de acordo com a dara break if not bool_2_grau: # Verificar se o processo está no segundo grau bool_2_grau= self.keywords_2_degree(string=desc_process) list_file_name = [] acp_pra_status = False print('.', end='') obs = "" # Obseração, a movimentação pode ter downoad mas pode está em sigilo ou colocado de forma equivocada if download: # Se existir donwload # os downloads ficam em uma tabela que tem o id = divArquivosMovimentacaoProcessomovimentacoes + numero da linha documento_valido = linha.find_elements_by_tag_name('strike') # Quando tem essa tag o documento foi exlcuido if len(documento_valido)>0: obs = " - Acompanhamento possui arquivo mas não pode ser acessado: os motivos possíveis são uma determinação judicial ou a sua inclusão no processo de forma equivocada." else: print("Numero evento: ", n_event, " ") self.pegar_linha_movimentacao(i).find_element_by_tag_name('img').click() # Clilcar para abrir os donwlads self.fazer_donwload('divArquivosMovimentacaoProcessomovimentacoes' + str(k-1),list_name_urls,list_file_name,obs) print('<>', end='') if len(self.browser.window_handles)>1: # Documento ainda não está disponível obs = "Documento ainda não está disponível." self.fechar_aba_atual_voltar_para_primeira() list_file_name.append(ProcessoArquivoModel(pra_erro=4)) list_acomp_download.append((AcompanhamentoModel(acp_esp=desc_process + obs, acp_numero=n_event, acp_data_cadastro=aux_data, acp_prc_id=prc_id), list_file_name)) qtd_erro = 0 except TimeoutException: if qtd_erro>2: raise self.browser.refresh() qtd_erro+=1 i+=2 #ARRUMAR DAQUI PARA BAIXO DEPOIS print('tam: {} | acompanhamento: {}'.format(len(list_name_urls), len(list_acomp_download))) if len(list_acomp_download)>0: list_audiences = TratarAudiencia.treat_audience(self.pegar_as_audiencias(),prc_id) return list_audiences, list_acomp_download, list_name_urls,bool_2_grau, err, not_refresh
def acomp_down_aud(self, prc_id, ult_mov,bool_2_grau_numero,full): list_acomp_download = [] file_downloaded = None list_file_path = [] list_audiences = [] list_name_urls = [] list_references = [] list_2_grau_numero = [] not_refresh = 0 err = False t = 0 # PERCORRE A TABELA E FAZ O DOWNLOAD REFERENTE A CADA ACOMPANHAMENTO try : aux_data = self.browser.find_elements_by_xpath('//*[@id="tblEventos"]/tbody/tr[1]/td[2]') if len(aux_data) == 0: input("\n\n\n\t\t\t\t\t(//*[@id='tblEventos']/tbody/tr[1]/td[2])\n\n\n\n\n") raise aux_data = Tools.treat_date(aux_data[0].text) if ult_mov is not None: not_refresh += 1 if aux_data <= ult_mov: return list_audiences, list_acomp_download, list_name_urls, list_2_grau_numero, err, not_refresh aux_click = self.browser.find_elements_by_xpath('//*[@id="infraAjaxCarregarPaginasNormal"]/a[2]') if len(aux_click)>0: aux_click[0].click() wait = WebDriverWait(self.browser, 3) wait.until(EC.invisibility_of_element((By.ID,'infraAjaxCarregarPaginasNormal'))) movimentos = self.browser.find_elements_by_xpath('//*[@id="tblEventos"]/tbody/tr') for movimento in movimentos : aux_data = Tools.treat_date(movimento.find_element_by_xpath('td[2]').text) if ult_mov is not None : not_refresh += 1 if aux_data <= ult_mov : break desc_process = movimento.find_element_by_xpath('td[3]').text.upper() desc_process = Tools.remove_accents(desc_process) if "Distribuido Agravo de Instrumento" in desc_process \ or "Distribuido Recurso Inominado" in desc_process \ or "Distribuido Apelacao / Reexame Necessario" in desc_process : number_2_grau = desc_process.split(":")[-1] number_2_grau = number_2_grau.split('/')[0] number_2_grau = re.sub("[^0-9]", '', number_2_grau) if number_2_grau not in list_2_grau_numero : list_2_grau_numero.append(number_2_grau) n_event = int(movimento.find_element_by_xpath('td[1]').text) # print("n_event->",n_event) # REALIZA O DOWNLOAD DOS ANEXOS DE CADA ACOMPANHAMENTO list_files_to_download = movimento.find_elements_by_class_name('infraLinkDocumento') list_file_name = [] acp_pra_status = None if len(list_files_to_download) : for file in list_files_to_download : tipo_arq = file.get_attribute("data-mimetype") print(f'tipo_arq = {tipo_arq}') try: coordinate = file.location_once_scrolled_into_view self.browser.execute_script( 'window.scrollTo({}, {});'.format(coordinate['x'], coordinate['y'])) file.click() n_files = len(os.listdir(self.path_download_prov)) t += 1 wait = WebDriverWait(self.browser, 2) wait.until(EC.number_of_windows_to_be(2)) self.browser.switch_to_window(self.browser.window_handles[-1]) if ("mp3" not in tipo_arq) and ("wma" not in tipo_arq): try: iframe = self.browser.find_elements_by_id("conteudoIframe") except: input("323") raise main_content=[] if len(iframe): self.browser.switch_to.frame(iframe[0]) main_content = self.browser.find_elements_by_xpath('//*[@id="main-content"]/a') if len(main_content): main_content[0].click() self.browser.close() self.browser.switch_to_window(self.browser.window_handles[0]) err_down = self.wait_download(n_files) else: completeName = os.path.join(self.path_download_prov, Tools.convert_base(str(datetime.now()))) file_object = codecs.open(completeName + '.html', "w", "utf-8") html = self.browser.page_source file_object.write(html) self.browser.close() self.browser.switch_to_window(self.browser.window_handles[0]) # vai para última aba err_down = False except: self.browser.switch_to_window(self.browser.window_handles[0]) self.log_error.insert_log('Download do arquivo: evento {}!'.format(n_event)) err_down = True # input("deu erro ") # raise acp_pra_status = acp_pra_status and (not err_down) nome = Tools.convert_base(str(datetime.now())) desc_file = None if not err_down: for arq in os.listdir(self.path_download_prov): if arq not in list_file_path: list_file_path.append(arq) file_downloaded = arq break nome = Tools.convert_base(str(datetime.now())) list_name_urls.append((nome, file_downloaded)) ext = file_downloaded.split('.')[-1].lower() nome = nome + '.' + ext desc_file = file_downloaded.split('.')[0] list_file_name.append(ProcessoArquivoModel(pra_prc_id=prc_id, pra_nome=nome, pra_descricao=desc_file, pra_erro=err_down)) # VERIFICA SE A SESSÃO FOI ENCERRADA if ("mp3" not in tipo_arq and "wma"not in tipo_arq )and len(self.browser.window_handles) > 1: self.browser.switch_to_window(self.browser.window_handles[1]) input("deseja continuar {}".format(len(self.browser.window_handles))) self.browser.close() acp_pra_status = False self.browser.switch_to_window(self.browser.window_handles[0]) list_acomp_download.append((AcompanhamentoModel(acp_esp=desc_process, acp_numero=n_event,acp_tipo=n_event, acp_data_cadastro=aux_data, acp_prc_id=prc_id), list_file_name)) # BUSCA AS AUDIÊNCIAS t=time.time() self.buscar_as_audiencia(list_audiences=list_audiences,list_references=list_references, movimentos=movimentos,n_event=n_event) # print(' Tempo -> ',time.time()-t) list_audiences = self.treat_audience(list_audiences=list_audiences,prc_id=prc_id) except : list_acomp_download.clear() list_name_urls.clear() list_audiences.clear() list_2_grau_numero.clear() self.log_error.insert_log('coleta de dados dos acompanhamentos do processo!'.upper()) err = True raise # print(len(list_acomp_download), '->len(list_acomp_download)') return list_audiences, list_acomp_download, list_name_urls, list_2_grau_numero, err, not_refresh
def acomp_down_aud(self, prc_id, ult_mov, bool_2_grau_numero): list_acomp_download = [] file_downloaded = None list_file_path = [] list_audiences = [] list_name_urls = [] not_refresh = 0 bool_2_grau = bool_2_grau_numero err = False t = 0 k = 0 try: movimentos = self.browser.find_elements_by_xpath( '//*[@id="Arquivos"]/table/tbody/tr')[1:] for i in range(len(movimentos)): k += 1 aux_data = movimentos[i].find_element_by_xpath( 'td/table/tbody/tr/td[5]').text aux_data = Tools.treat_date(aux_data) if ult_mov is not None: not_refresh += 1 if aux_data <= ult_mov: break desc_process = movimentos[i].find_element_by_xpath( 'td/table/tbody/tr/td[4]').text.upper() desc_process = Tools.remove_accents(desc_process) if not bool_2_grau: aux = desc_process.upper() bool_2_grau = 'RECURSO AUTUADO' in aux if bool_2_grau: print(aux) n_event = movimentos[i].find_element_by_xpath( 'td/table/tbody/tr/td[3]').text # PEGAR AS AUDIÊNCIAS audiences = desc_process.split(' ') if 'AUDIENCIA' in audiences[0]: list_audiences.append(desc_process.split('AUDIENCIA ')[-1]) # REALIZA O DOWNLOAD list_file_name = [] acp_pra_status = False try: movimentos[i].find_element_by_xpath( 'td/table/tbody/tr/td[8]/div/div/table/tbody/tr/' 'td[1]/a').click() wait = WebDriverWait(self.browser, 60) wait.until( EC.visibility_of_all_elements_located( (By.XPATH, '//*[@id="Arquivos"]/table/tbody/' 'tr[{}]/td/span[2]/div/div/table/tbody/' 'tr'.format(i + 2)))) # BAIXA OS ANEXOS E CRIA ACOMPANHAMENTO ASSOCIANDO OS ANEXOS CONTIDOS NELES ul_files = movimentos[i].find_elements_by_xpath( 'td/span[2]/div/div/table/tbody/tr') for file in enumerate(ul_files): try: n_files = len(os.listdir(self.path_download_prov)) if file[0] != 0: file[1].find_element_by_xpath( 'td[4]/a').click() else: file[1].find_element_by_xpath( 'td[5]/a').click() t += 1 err_down = self.wait_download(n_files) try: # VERIFICA SE A SESSÃO FOI ENCERRADA if len(self.browser.window_handles) > 1: if self.browser is not None: self.browser.switch_to_window( self.browser.window_handles[1]) self.browser.close() self.browser.switch_to_window( self.browser.window_handles[0]) acp_pra_status = False except: self.log_error.insert_log( 'Download do arquivo: evento {}!'.format( n_event)) acp_pra_status = False err = True break if not err_down: try: if file[0] != 0: desc_file = file[ 1].find_element_by_xpath( 'td[4]/a').text else: desc_file = file[ 1].find_element_by_xpath( 'td[5]/a').text except: desc_file = None for arq in os.listdir(self.path_download_prov): if arq not in list_file_path: list_file_path.append(arq) file_downloaded = arq break nome = Tools.convert_base(str(datetime.now())) list_name_urls.append((nome, file_downloaded)) ext = file_downloaded.split('.')[-1].lower() nome = nome + '.' + ext list_file_name.append( ProcessoArquivoModel( pra_prc_id=prc_id, pra_nome=nome, pra_descricao=desc_file)) acp_pra_status = True else: self.log_error.insert_log( 'Download do arquivo: evento {}!'.format( n_event)) acp_pra_status = False except: self.log_error.insert_log( 'Download do arquivo: evento {}!'.format( n_event)) acp_pra_status = False except: pass list_acomp_download.append([ AcompanhamentoModel(acp_esp=desc_process, acp_numero=n_event, acp_data_cadastro=aux_data, acp_prc_id=prc_id), list_file_name ]) print('tam: {} | file: {}'.format(len(list_name_urls), t)) # PEGA AS AUDIÊNCIAS APÓS ULTIMA DATA DE MOVIMENTAÇÃO DOS ACOMPANHAMENTOS for j in range(len(movimentos[k + 1:])): desc_process = movimentos[j].find_element_by_xpath( 'td/table/tbody/tr/td[4]').text.upper() desc_process = Tools.remove_accents(desc_process) audiences = desc_process.split(' ') if 'AUDIENCIA' in audiences[0]: list_audiences.append(desc_process.split('AUDIENCIA ')[-1]) try: # TRATA AS AUDIÊNCIAS dict_audiences = {} list_audiences.reverse() tipo = None status = None for i in range(len(list_audiences)): aud = list_audiences[i].split('\n') aud_split = aud[0].split(' ') if 'AUDIENCIA' in aud_split[0]: continue if 'CEJUSC' in aud_split: aud_split.remove('CEJUSC') try: if 'DE' in aud_split[0]: del aud_split[0] except IndexError: pass if len(aud_split) > 2 and 'REALIZADA' not in aud_split: tipo = '' for l in aud_split[:-1]: tipo += l if not l == aud_split[-2]: tipo += ' ' tipo = tipo.upper() status = aud_split[-1].upper() elif 'REALIZADA' in aud_split: status = 'REALIZADA' elif 'NEGATIVA' in aud_split: status = 'NEGATIVA' elif 'CANCELADA' in aud_split: status = 'CANCELADA' elif len(aud_split) == 2: tipo = aud_split[0].upper() status = aud_split[1].upper() elif len(aud_split) > 0: status = aud_split[0].upper() print('tipo: {} - status: {}'.format(tipo, status)) if 'DESIGNADA' == status or 'MARCADA' == status: try: aux_data = aud[1].split('PARA ')[-1].split( ' )')[0].split(')')[0].split(', ')[0] aux_data = aux_data.lower() data = Tools.treat_date(aux_data) except: data = None if tipo in dict_audiences.keys( ) and dict_audiences[tipo].aud_status == status: dict_audiences[tipo].aud_data = data else: dict_audiences[tipo] = AudienciaModel( aud_tipo=tipo, aud_prc_id=prc_id, aud_status=status, aud_data=data) elif 'REDESIGNADA' in status or 'REMARCADA' in status: dict_audiences[tipo].aud_status = status dict_audiences[(tipo, i)] = dict_audiences[tipo] elif 'NEGATIVA' in status or 'CANCELADA' in status: dict_audiences[tipo].aud_status = status dict_audiences[(tipo, i)] = dict_audiences[tipo] elif 'REALIZADA' in status or 'PUBLICADA' in status: dict_audiences[tipo].aud_status = status try: obs = Tools.remove_accents( aud[1]).strip(' (').strip(')') except: obs = None dict_audiences[tipo].aud_obs = obs dict_audiences[(tipo, i)] = dict_audiences[tipo] list_audiences.clear() list_aux = [] for i in dict_audiences.values(): if id(i) not in list_aux: list_audiences.append(i) list_aux.append(id(i)) print('\n', i.aud_tipo, '\n', i.aud_status, '\n', i.aud_data, '\n', i.aud_obs, "\n") except: list_audiences.clear() self.log_error.insert_log( 'coleta de dados das audiências do processo!'.upper()) except: list_acomp_download.clear() list_audiences.clear() list_name_urls.clear() self.log_error.insert_log( 'coleta de dados dos acompanhamentos do processo!'.upper()) err = True bool_2_grau = False # raise return list_audiences, list_acomp_download, list_name_urls, bool_2_grau, err, not_refresh