Mundo em Python

Verificar Site

from tkinter import *
import requests
from time import time
from urllib.parse import urlparse # Função para validar a URL
def validar_url(url):
try:
resultado = urlparse(url)
return all([resultado.scheme, resultado.netloc])
except ValueError:
return False

# Função para limpar os campos
def limpar():
site_entrada.delete(0, END)
resultado_texto.config(text="")
cabecalhos_texto.config(state=NORMAL)
cabecalhos_texto.delete(1.0, END)
cabecalhos_texto.config(state=DISABLED)
historico_texto.config(state=NORMAL)
historico_texto.delete(1.0, END)
historico_texto.config(state=DISABLED) # Função para verificar o site
def app():
url = site.get()
if not validar_url(url):
resultado_texto.config(text="URL inválida! Certifique-se de incluir 'http://' ou 'https://'.", fg="red")
return

try:
inicio = time()
resposta = requests.get(url, timeout=5)
fim = time()
tempo_resposta = fim - inicio if resposta.status_code == 200:
mensagem = f"O site {url} está online!\nTempo de resposta: {tempo_resposta:.2f} segundos."
cor = "green"
else:
mensagem = f"O site {url} retornou um status inesperado: {resposta.status_code}."
cor = "orange"

# Verifica se o site usa HTTPS
if url.startswith("https://"):
mensagem += "\nO site é seguro (HTTPS)."
else:
mensagem += "\nO site não utiliza HTTPS."

# Exibe os cabeçalhos de resposta
cabecalhos_texto.config(state=NORMAL)
cabecalhos_texto.delete(1.0, END)
for chave, valor in resposta.headers.items():
cabecalhos_texto.insert(END, f"{chave}: {valor}\n")
cabecalhos_texto.config(state=DISABLED) # Salva no histórico
with open("historico.txt", "a") as historico_file:
historico_file.write(f"{url}\n")
historico_texto.config(state=NORMAL)
historico_texto.insert(END, f"{url}\n")
historico_texto.config(state=DISABLED) except requests.exceptions.ConnectionError:
mensagem = f"Não foi possível conectar ao site {url}."
cor = "red"
except requests.exceptions.Timeout:
mensagem = f"O site {url} demorou muito para responder."
cor = "red"
except requests.exceptions.RequestException as e:
mensagem = f"Um erro ocorreu ao verificar o site {url}: {e}"
cor = "red"
# Log do erro
with open("error_log.txt", "a") as log_file:
log_file.write(f"Erro ao verificar {url}: {e}\n") # Exibe o resultado
resultado_texto.config(text=mensagem, fg=cor) # Função para salvar o conteúdo HTML
def salvar_html():
url = site.get()
if not validar_url(url):
resultado_texto.config(text="URL inválida! Certifique-se de incluir 'http://' ou 'https://'.", fg="red")
return

try:
resposta = requests.get(url, timeout=5)
if resposta.status_code == 200:
with open("pagina.html", "w", encoding="utf-8") as html_file:
html_file.write(resposta.text)
resultado_texto.config(text=f"O conteúdo da página foi salvo como 'pagina.html'.", fg="green")
else:
resultado_texto.config(text=f"Falha ao acessar o site {url}.", fg="red")
except requests.exceptions.RequestException as e:
resultado_texto.config(text=f"Erro ao tentar salvar o conteúdo do site: {e}", fg="red") # Configuração da Janela
root = Tk()
root.geometry("900x600")
root.resizable(0, 0)
root.config(bg="#103030")
root.title("Verificar Site") # Título
titulo = Label(text="Verificar Site", font=("Arial", 40, "bold"), bg="#103030", fg="#49e3e3")
titulo.place(relx=0.3, rely=0.05) # Subtítulo
texto_sub1 = Label(text="URL do site (inclua http:// ou https://):", font=("Arial", 18, "bold"), bg="#103030", fg="#49e3e3")
texto_sub1.place(relx=0.05, rely=0.15) # Entrada de URL
site = StringVar()
site_entrada = Entry(textvariable=site, font=("Arial", 12, "bold"), bg="white", fg="blue", justify='center')
site_entrada.place(relx=0.55, rely=0.15, relwidth=0.4)
site_entrada.focus() # Botões
but1 = Button(text="Verificar", bd=2, bg='#107db2', fg='white', font=('verdana', 12, 'bold'), command=app)
but1.place(relx=0.1, rely=0.3, relwidth=0.25, relheight=0.1) but_html = Button(text="Salvar HTML", bd=2, bg='#107db2', fg='white', font=('verdana', 12, 'bold'), command=salvar_html)
but_html.place(relx=0.4, rely=0.3, relwidth=0.25, relheight=0.1) but_limpar = Button(text="Limpar", bd=2, bg='#107db2', fg='white', font=('verdana', 12, 'bold'), command=limpar)
but_limpar.place(relx=0.7, rely=0.3, relwidth=0.25, relheight=0.1) but_sair = Button(text="Sair", bd=2, bg='#107db2', fg='white', font=('verdana', 12, 'bold'), command=root.destroy)
but_sair.place(relx=0.4, rely=0.45, relwidth=0.25, relheight=0.1) # Resultado
resultado_texto = Label(text="", font=("Arial", 12, "bold"), bg="#cfe2f3", wraplength=800, justify="left")
resultado_texto.place(relx=0.05, rely=0.6, relwidth=0.9, relheight=0.1) # Cabeçalhos de resposta
cabecalhos_label = Label(text="Cabeçalhos HTTP:", font=("Arial", 14, "bold"), bg="#103030", fg="#49e3e3")
cabecalhos_label.place(relx=0.05, rely=0.72) cabecalhos_texto = Text(font=("Arial", 12), bg="#cfe2f3", fg="black", height=8, width=50)
cabecalhos_texto.place(relx=0.55, rely=0.72, relwidth=0.4, relheight=0.2)
cabecalhos_texto.config(state=DISABLED) # Histórico
historico_label = Label(text="Histórico de Verificações:", font=("Arial", 14, "bold"), bg="#103030", fg="#49e3e3")
historico_label.place(relx=0.05, rely=0.92) historico_texto = Text(font=("Arial", 12), bg="#cfe2f3", fg="black", height=8, width=50)
historico_texto.place(relx=0.55, rely=0.92, relwidth=0.4, relheight=0.2)
historico_texto.config(state=DISABLED) root.mainloop()
0