Advertisement
MizunoBrasil

Raspagem Globo 2 (exporta html)

Feb 15th, 2024
1,000
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.81 KB | None | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. from datetime import datetime
  5.  
  6. def extrair_informacao(url):
  7.     # Faz uma solicitação HTTP para a URL fornecida
  8.     response = requests.get(url)
  9.    
  10.     # Verifica se a solicitação foi bem-sucedida
  11.     if response.status_code == 200:
  12.         # Cria um objeto BeautifulSoup para fazer o parsing do conteúdo HTML
  13.         soup = BeautifulSoup(response.content, 'html.parser')
  14.        
  15.         # Extrai o título da página
  16.         title = soup.title.string
  17.        
  18.         # Extrai a primeira frase de texto da página
  19.         first_paragraph = soup.find('p').text.strip()
  20.        
  21.         # Extrai o texto da seção content-head__subtitle
  22.         subtitle = soup.find(class_='content-head__subtitle').text.strip()
  23.        
  24.         # Retorna as informações extraídas
  25.         return title, first_paragraph, subtitle, url
  26.     else:
  27.         print("Falha ao fazer a solicitação HTTP.")
  28.         return None, None, None, None
  29.  
  30. def main():
  31.     # Solicita ao usuário que insira a URL
  32.     url = input("Por favor, insira a URL da página que deseja extrair informações: ")
  33.    
  34.     # Extrai informações da página
  35.     title, first_paragraph, subtitle, url = extrair_informacao(url)
  36.    
  37.     # Imprime as informações extraídas
  38.     if title and first_paragraph and subtitle and url:
  39.         print("", title)
  40.         print("", first_paragraph)
  41.         print("", subtitle)
  42.         print("URL da página:", url)
  43.        
  44.         # Remove caracteres inválidos do título da página para usar como nome do arquivo
  45.         filename = re.sub(r'[^\w\s-]', '', title)
  46.         filename = filename.replace(' ', '_')  # Substitui espaços em branco por underscore
  47.         filename += f"_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.html"
  48.        
  49.         # Exporta as informações para um arquivo .html
  50.         with open(filename, 'w', encoding='utf-8') as file:
  51.             file.write("<!DOCTYPE html>\n")
  52.             file.write("<html>\n<head>\n<title>" + title + "</title>\n")
  53.             file.write("<style>\n")
  54.             file.write("body { font-family: Arial, sans-serif; }\n")
  55.             file.write(".subtitle { color: blue; }\n")
  56.             file.write("</style>\n")
  57.             file.write("</head>\n<body>\n")
  58.             file.write("<h1>" + title + "</h1>\n")
  59.             file.write("<p>" + first_paragraph + "</p>\n")
  60.             file.write("<p class='subtitle'>" + subtitle + "</p>\n")
  61.             file.write("<p>URL da página: <a href='" + url + "' target='_blank'>" + url + "</a></p>\n")
  62.             file.write("</body>\n</html>")
  63.        
  64.         print(f"As informações foram exportadas para o arquivo: {filename}")
  65.     else:
  66.         print("Não foi possível extrair informações da página.")
  67.  
  68. if __name__ == "__main__":
  69.     main()
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement