HTML Parser - Part 2 Answer

This Python program is designed to parse HTML input. It uses the HTMLParser module from Python's standard library to create a custom parser. The parser is capable of distinguishing between single-line and multi-line comments, as well as handling data within the HTML.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the HTML Parser - Part 2 Answer HackerRank solution using CodeRankGPT:

The solution works by creating a custom HTML parser that overrides the handle_comment and handle_data methods from the HTMLParser class. The handle_comment method checks if the comment is a single-line or multi-line comment by counting the number of lines in the comment. The handle_data method handles the data within the HTML. The parser then reads HTML input line by line, feeds it to the parser, and prints the parsed output.


from html.parser import HTMLParser

class CustomHTMLParser(HTMLParser):
    def handle_comment(self, data):
        number_of_line = len(data.split("\n"))
        if number_of_line > 1:
            print(">>> Multi-line Comment")
        else:
            print(">>> Single-line Comment")
        if data.strip():
            print(data)

    def handle_data(self, data):
        if data.strip():
            print(">>> Data")
            print(data)


parser = CustomHTMLParser()

n = int(input())

html_string = "".join(input().rstrip() + "\n" for _ in range(n))
parser.feed(html_string)
parser.close()

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform