Advertisement
Python253

html2json

Mar 13th, 2024
753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: html2json.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts an HTML file (.html) to a JSON file (.json).
  10. It uses BeautifulSoup to parse the HTML content and saves the prettified HTML as a JSON file.
  11.  
  12. Requirements:
  13. - Python 3.x
  14. - BeautifulSoup library (install using: pip install beautifulsoup4)
  15.  
  16. Usage:
  17. 1. Save this script as 'html2json.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 converted JSON file ('html2json.json') will be generated in the same directory.
  22.  
  23. Note: Adjust the 'html_filename' and 'json_filename' variables in the script as needed.
  24. """
  25. import json
  26. from bs4 import BeautifulSoup
  27.  
  28. def html_to_json(html_filename, json_filename):
  29.     with open(html_filename, 'r') as htmlfile, open(json_filename, 'w') as jsonfile:
  30.         soup = BeautifulSoup(htmlfile, 'html.parser')
  31.         data = {"html_content": soup.prettify()}
  32.         json.dump(data, jsonfile, indent=2)
  33.  
  34. if __name__ == "__main__":
  35.     html_filename = 'example.html'
  36.     json_filename = 'html2json.json'
  37.     html_to_json(html_filename, json_filename)
  38.     print(f"Converted '{html_filename}' to '{json_filename}'.")
  39.  
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement