Advertisement
Python253

html2txt

Mar 13th, 2024
723
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: html2txt.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script extracts text content from an HTML file (.html) and saves it to a text file (.txt).
  10. It uses BeautifulSoup to parse the HTML content and extracts the text using the 'get_text' method.
  11.  
  12. Requirements:
  13. - Python 3.x
  14. - BeautifulSoup library (install using: pip install beautifulsoup4)
  15.  
  16. Usage:
  17. 1. Save this script as 'html2txt.py'.
  18. 2. Ensure your HTML file ('example.html') is in the same directory as the script.
  19. 3. Install the BeautifulSoup library using the command: 'pip install beautifulsoup4'
  20. 4. Run the script.
  21. 5. The extracted text file ('html2txt.txt') will be generated in the same directory.
  22.  
  23. Note: Adjust the 'html_filename' and 'txt_filename' variables in the script as needed.
  24. """
  25. from bs4 import BeautifulSoup
  26.  
  27. def html_to_txt(html_filename, txt_filename):
  28.     with open(html_filename, 'r') as htmlfile, open(txt_filename, 'w') as txtfile:
  29.         soup = BeautifulSoup(htmlfile, 'html.parser')
  30.         txtfile.write(soup.get_text('\n'))
  31.  
  32. if __name__ == "__main__":
  33.     html_filename = 'example.html'
  34.     txt_filename = 'html2txt.txt'
  35.     html_to_txt(html_filename, txt_filename)
  36.     print(f"Converted '{html_filename}' to '{txt_filename}'.")
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement