Problem Name: Python - Detect HTML Tags, Attributes and Attribute Values

Problem Link:  

In this HackerRank Functions in PYTHON problem solution,

You are given an HTML code snippet of N lines.
Your task is to detect and print all the HTML tags, attributes and attribute values.

Print the detected items in the following format:


-> Attribute2[0] > Attribute_value2[0]
-> Attribute2[1] > Attribute_value2[1]
-> Attribute2[2] > Attribute_value2[2]
-> Attribute3[0] > Attribute_value3[0]




The -> symbol indicates that the tag contains an attribute. It is immediately followed by the name of the attribute and the attribute value.
The > symbol acts as a separator of attributes and attribute values.


If an HTML tag has no attribute then simply print the name of the tag.


Note: Do not detect any HTML tag, attribute or attribute value inside the HTML comment tags (<!-- Comments -->). Comments can be multiline.
All attributes have an attribute value.

Input Format

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


0 < N < 100

Output Format

Print the HTML tags, attributes and attribute values in order of their occurrence from top to bottom in the snippet.

Format your answers as explained in the problem statement.

Sample Input

<object type="application/x-flash" 
  width="0" height="0">
  <!-- <param name="movie" value="your-file.swf" /> -->
  <param name="quality" value="high"/>

Sample Output

-> type > application/x-flash
-> data > your-file.swf
-> width > 0
-> height > 0
-> name > quality
-> value > high


  • head tag: Print the head tag only because it has no attribute.

  • title tag: Print the title tag only because it has no attribute.

  • object tag: Print the object tag. In the next 4
  • lines, print the attributes type, data, width and height along with their respective values.

  • <!-- Comment --> tag: Don't detect anything inside it.

  • param tag: Print the param tag. In the next 2 lines, print the attributes name along with their respective values.




Code Examples

#1 Code Example with Python Programming

Code - Python Programming

from html.parser import HTMLParser

# Same approach as the HTML Parser 1 Challenge! Make a subclass and override methods
N = int(input())
class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attributes):
        [print('-> {} > {}'.format(*attribute)) for attribute in attributes]
html = '\n'.join([input() for x in range(0, N)])  
parser = MyHTMLParser()
Copy The Code & Try With Live Editor


[Solved] HTML Parser - Part 2 in PYTHON solution in Hackerrank
[Solved] XML 1 - Find the Score in PYTHON solution in Hackerrank