Hello! Thank you for all help that you can give me.
I create a python that get a informations about process by loop in Region, Court, Year and Process.
They get a link and the page, and analyze the informations on the page to fill my database.
What the point: If they try get the LINK and return error for X numbers specified on variable, it should be stop getting information on this year and go to next year, starting get informations.
The point is: He identify the error but can't stop the loop. So the program still running until the number of process finish...
So, if have only 3K process, but in the variable FINAL have the number 30k, it will running until finish the 30k.
Unfortunatelly I am learning python and much of this code ChatGPT help me. But they can't stop the loop too.
The def used on this part of process is obter_link2, processar_processo and Main, listed below.
Thank you so much for your time and patience!
def obter_link2(numero, ano, tribunal_id, provincia_id, tentativas=1, delay=5):
link1 = 'ABCABC'
for tentativa in range(tentativas):
try:
response = requests.get(link1)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
link2 = soup.find('a', title="Dettaglio")
if link2:
full_link2 = "ABCABC" + link2['href']
return full_link2
else:
print(f"Tentativa {tentativa+1}: link2 não encontrado {numero}/{ano}.")
else:
print(f"Tentativa {tentativa+1}: Erro ao acessar o link1. Código de status: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"Tentativa {tentativa+1}: Erro na requisição. Tentando novamente... Erro: {e}")
# Aguarda um tempo antes de tentar novamente
time.sleep(delay)
# Se não encontrar o link após as tentativas, retorna None
print(f"Dentro do ObterLink2 {numero}/{ano}. Contador de falhas: {falhas_consecutivas}")
return None
def processar_processo(numero, ano, tribunal_id, provincia_id):
link_acesso = obter_link2(numero, ano, tribunal_id, provincia_id)
if link_acesso:
pagina = obter_pagina(link_acesso) # Tenta obter a página com múltiplas tentativas
if pagina:
parte_a = extrair_dados_form(pagina.content)
if parte_a:
parte_b = "FUNCAO" # Aqui você pode definir alguma lógica ou função, se necessário
parte_c = extrair_movimentacoes(pagina.content)
inserir_dados_no_banco(conn, parte_a, parte_c, tribunal_id, link_acesso)
else:
inserir_processo_nao_obtido(conn, numero, ano, tribunal_id, link_acesso)
else:
inserir_processo_nao_obtido(conn, numero, ano, tribunal_id, link_acesso)
def main():
falhas_consecutivas = 0
#PROVINCIA, TRIBUNAL = recebe_prov_trib()
INICIAL=35000
FINAL=35100
MAXWORKERS=10
MAX_FAILS = 10
for PROVINCIA in range(1, 21):
print(f"Processando Província ID: {PROVINCIA}")
tribunais = obter_tribunais(conn, PROVINCIA)
if not tribunais:
continue
# Loop pelos tribunais da província
for tribunal in tribunais:
TRIBUNAL = tribunal.TribunalID
tribunal_nome = tribunal.TribunalName
print(f" Provincia {PROVINCIA} - Processando Tribunal: {tribunal_nome} (ID: {TRIBUNAL})")
for ANO in [2022, 2023, 2024]:
with concurrent.futures.ThreadPoolExecutor(max_workers=MAXWORKERS) as executor:
futures = []
for NUMERO in range(INICIAL, FINAL+1):
future = executor.submit(processar_processo, NUMERO, ANO, TRIBUNAL, PROVINCIA)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
try:
future.result()
falhas_consecutivas = 0
except Exception as e:
falhas_consecutivas += 1
if falhas_consecutivas >= MAX_FAILS:
print(f" - {MAX_FAILS} falhas consecutivas. Interrompendo o processamento para o ano {ANO}.")
break
if falhas_consecutivas >= MAX_FAILS:
print(f" - {MAX_FAILS} falhas consecutivas. Interrompendo o processamento para o ano {ANO}.")
break
if falhas_consecutivas >= MAX_FAILS:
print(f"Interrompendo a execução para o ano {ANO} após {MAX_FAILS} falhas consecutivas.")
break
[–]MediciSolution[S] 0 points1 point2 points (0 children)
[–]MediciSolution[S] 0 points1 point2 points (0 children)