The Wayback Machine - https://web.archive.org/web/20240724014150/https://www.geeksforgeeks.org/convert-html-source-code-to-json-object-using-python/
Open In App

Convert HTML source code to JSON Object using Python

Last Updated : 03 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. 

We will use xmltojson module in this post. The parse function of this module takes the HTML as the input and returns the parsed JSON string.

Syntax: xmltojson.parse(xml_input, xml_attribs=True, item_depth=0, item_callback)

Parameters:

  • xml_input can be either a file or a string.
  • xml_attribs will include attributes if set to True. Otherwise, ignore them if set to False.
  • item_depth is the depth of children for which item_callback function is called when found.
  • item_callback is a callback function

Environment Setup:

Install the required modules :

pip install xmltojson
pip install requests

Steps:

  • Import the libraries

Python3




import xmltojson
import json
import requests


  • Fetch the HTML code and save it into a file.

Python3




# Sample URL to fetch the html page
  
# Headers to mimic the browser
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 \
    (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
  
# Get the page through get() method
html_response = requests.get(url=url, headers = headers)
  
# Save the page content as sample.html
with open("sample.html", "w") as html_file:
    html_file.write(html_response.text)


  • Use the parse function to convert this HTML into JSON. Open the HTML file and use the parse function of xmltojson module.

Python3




with open("sample.html", "r") as html_file:
    html = html_file.read()
    json_ = xmltojson.parse(html)


  • The json_ variable contains a JSON string that we can print or dump into a file.

Python3




with open("data.json", "w") as file:
    json.dump(json_, file)


  • Print the output.

Python3




print(json_)


Complete Code:

Python3




import xmltojson
import json
import requests
  
  
# Sample URL to fetch the html page
  
# Headers to mimic the browser
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 \
    (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
  
# Get the page through get() method
html_response = requests.get(url=url, headers = headers)
  
# Save the page content as sample.html
with open("sample.html", "w") as html_file:
    html_file.write(html_response.text)
      
with open("sample.html", "r") as html_file:
    html = html_file.read()
    json_ = xmltojson.parse(html)
      
with open("data.json", "w") as file:
    json.dump(json_, file)
      
print(json_)


Output:

{“html”: {“@lang”: “en”, “head”: {“title”: “Document”}, “body”: {“div”: {“h1”: “Geeks For Geeks”, “p”: 

“Welcome to the world of programming geeks!”, “input”: [{“@type”: “text”, “@placeholder”: “Enter your name”}, 

{“@type”: “button”, “@value”: “submit”}]}}}}



Similar Reads

Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
Convert class object to JSON in Python
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
2 min read
Convert Generator Object To JSON In Python
JSON (JavaScript Object Notation) is a widely used data interchange format, and Python provides excellent support for working with JSON data. However, when it comes to converting generator objects to JSON, there are several methods to consider. In this article, we'll explore some commonly used methods. Convert Generator Object To JSON In PythonBelo
2 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
How to retrieve source code from Python objects?
We are given a object and our task is to retrieve its source code, for this we have inspect module, dill module and dis module built-in standard libraries in Python programming. They provide several useful functions to track information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. get
2 min read
Python Flask Projects with Source Code (Beginners to Advanced)
Flask, a Python web application framework, was created by Armin Ronacher. Known for its lightweight and efficient nature, Flask is designed for quick starts and accommodates complex applications. It is based on the Werkzeug WSGI toolkit and Jinja2 template engine. In this article, we’ve curated a list of the best Python Flask projects for all skill
4 min read
Python Django Projects with Source Code (Beginners to Advanced)
Python Django Projects with Source Code - Adding a project portfolio to your resume helps to show your skills and potential to your recruiter. Because in the tech space, real-time project experience matters a lot. Now, to make your resume powerful, we have come up with the top Django projects with source code. Here, you will find three levels of th
5 min read
Top 10 Django Projects For Beginners With Source Code
When it comes to software development in general, all development is run by websites on the internet. Even when you aren’t actively looking for web development or a Full stack developer role, having worked on Django Projects or any web development projects will substantially improve your portfolio regardless. This is because working and deploying a
8 min read
Deserialize JSON to Object in Python
Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module to perform this task : loads() : to deserialize a
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg