KatInterview

Extract Text From Matching Elements in Messy Markup

Trees & GraphsAuto-graded · 25 test cases
MediumAuto-gradedTrees & Graphsparsingtreedfs

Last updated

Parse a forgiving HTML string into an element tree in one pass, then collect each matching element's combined text in document order using an iterative depth-first traversal.

Extract Text From Matching Elements in Messy Markup

Given a string of HTML-like markup and a tag name, return the combined text of every element with that tag name, in document order.

An element's text is all the text inside it, including text in nested elements, concatenated in the order it appears. Whitespace is preserved exactly.

For example, in <p>Hello <b>world</b></p> the text of the p element is "Hello world".

Parsing rules

Scan the input left to right and keep a stack of currently open elements. The parser must be forgiving and follow these rules exactly.

  1. Text. Any run of characters outside tags is text and belongs to the innermost open element. Character entities (such as &amp; or &lt;) are decoded the way Python's html.unescape decodes them.
  2. Comments. <!-- starts a comment that ends at the first following -->. Comments are ignored. An unterminated comment swallows the rest of the input.
  3. Declarations. Anything starting with <! (such as a doctype, matched case-insensitively) or <? is ignored up to and including the next >. If there is no >, it swallows the rest of the input.
  4. End tags. </, then optional whitespace, then a name, forms an end tag. A name starts with an ASCII letter and continues with letters, digits, :, _ or -. Names are case-insensitive. The end tag is consumed through the next > (or to the end of input if there is none). It closes the nearest open element with that name, and any elements opened inside it are closed too. If no open element has that name, the end tag is ignored.
  5. Start tags. <, then optional whitespace, then a name (same name rules as above) begins a start tag. The tag extends to the next >.
    • If there is no > anywhere after it, the remaining input starting at that < is treated as plain text (entity-decoded) of the innermost open element, and parsing stops.
    • Otherwise a new element, named in lowercase, becomes a child of the innermost open element.
    • The new element stays open (later content nests inside it) unless it is a void element, or the tag is self-closing, or it is script/style. In those cases it is closed immediately.
    • Void elements are: area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr.
    • A tag is self-closing if the characters between the name and the >, after removing trailing whitespace, end with /.
  6. script and style. After the start tag, everything up to the next matching end tag (</, optional whitespace, the same name, optional whitespace, >, matched case-insensitively) is the element's only text. It is taken raw: no entity decoding and no markup parsing. If there is no matching end tag, the text runs to the end of the input. The matching end tag is consumed, and the element is closed.
  7. Stray <. Any < that does not begin a construct above (for example < followed by a space and a digit, or </>) is a literal < character of text. Parsing continues with the next character.

Query

Compare tag_name to element names case-insensitively. Return a list with one string per element that has that name. Order the elements by the position of their start tags, so an outer element comes before elements nested inside it. If matching elements are nested, each one is reported with its own full text. An element with no text contributes "". If nothing matches, return [].

Constraints

  • markup has length from 0 to about 10^5 and may be malformed in the ways described above.
  • tag_name is a non-empty name made of letters and digits.
  • Nesting can be deep, so avoid relying on recursion.
  • Aim for time roughly linear in the input length, not counting the cost of building long result strings.

Examples

Example 1

Input: collect_tag_texts('<div class="card"><p>Hello <b>world</b></p><br><p>Fish &amp; chips</p></div>', 'p')

Output: ['Hello world', 'Fish & chips']

Example 2

Input: collect_tag_texts('<div class="card"><p>Hello <b>world</b></p><br><p>Fish &amp; chips</p></div>', 'b')

Output: ['world']

Example 3

Input: collect_tag_texts('<ul><li>One</li><li>Two <strong>items</strong></li></ul>', 'li')

Output: ['One', 'Two items']

Hints

Hint 1

Use a stack of open elements. Each start tag attaches a node to the stack top and is pushed unless it is void, self-closing, or script/style.

Hint 2

For an end tag, search the stack from the top for the nearest element with that name and pop everything above it too. If there is none, ignore the tag.

Hint 3

Compute each node's text from its children's text (children before parents), then walk the tree in preorder and output the text of nodes whose name matches. Use explicit stacks to avoid recursion limits.