HTML Parser – Part 2 in Python | HackerRank Solution

Hello coders, today we are going to solve HTML Parser – Part 2 HackerRank Solution in Python.


This method is called when a comment is encountered (e.g. <!–comment–>).
The data argument is the content inside the comment tag:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_comment(self, data):
          print "Comment  :", data

This method is called to process arbitrary data (e.g. text nodes and the content of <script>…</script> and <style>…</style>).
The data argument is the text content of HTML.

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        print "Data     :", data


You are given an HTML code snippet of N lines.
Your task is to print the single-line comments, multi-line comments and the data.

Print the result in the following format:

>>> Single-line Comment  
>>> Data                 
My Data
>>> Multi-line Comment  
>>> Data
My Data
>>> Single-line Comment:  

Note: Do not print data if data == '\n'.

Input Format

The first line contains integer N, the number of lines in the HTML code snippet.
The next N lines contains HTML code.


  • 0 < N < 100

Output Format

Print the single-line comments, multi-line comments and the data in order of their occurrence from top to bottom in the snippet.

Format the answers as explained in the problem statement.

Sample Input

<!--[if IE 9]>IE9-specific content
<div> Welcome to HackerRank</div>
<!--[if IE 9]>IE9-specific content<![endif]-->

Sample Output

>>> Multi-line Comment
[if IE 9]>IE9-specific content
>>> Data
 Welcome to HackerRank
>>> Single-line Comment
[if IE 9]>IE9-specific content<![endif]

Solution – HTML Parser – Part 2 in Python

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_comment(self, comment):
        if '\n' in comment:
            print('>>> Multi-line Comment')
            print('>>> Single-line Comment')


    def handle_data(self, data):
        if data == '\n': return
        print('>>> Data')
html = ""       
for i in range(int(input())):
    html += input().rstrip()
    html += '\n'
parser = MyHTMLParser()

Disclaimer: The above Problem (HTML Parser – Part 2) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published.