Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: html2json.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- This script converts an HTML file (.html) to a JSON file (.json).
- It uses BeautifulSoup to parse the HTML content and saves the prettified HTML as a JSON file.
- Requirements:
- - Python 3.x
- - BeautifulSoup library (install using: pip install beautifulsoup4)
- Usage:
- 1. Save this script as 'html2json.py'.
- 2. Ensure your HTML file ('example.html') is in the same directory as the script.
- 3. Install the BeautifulSoup library using the command: 'pip install beautifulsoup4'
- 4. Run the script.
- 5. The converted JSON file ('html2json.json') will be generated in the same directory.
- Note: Adjust the 'html_filename' and 'json_filename' variables in the script as needed.
- """
- import json
- from bs4 import BeautifulSoup
- def html_to_json(html_filename, json_filename):
- with open(html_filename, 'r') as htmlfile, open(json_filename, 'w') as jsonfile:
- soup = BeautifulSoup(htmlfile, 'html.parser')
- data = {"html_content": soup.prettify()}
- json.dump(data, jsonfile, indent=2)
- if __name__ == "__main__":
- html_filename = 'example.html'
- json_filename = 'html2json.json'
- html_to_json(html_filename, json_filename)
- print(f"Converted '{html_filename}' to '{json_filename}'.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement