Extract Text From Matching Elements in Messy Markup
Trees & GraphsAuto-graded · 25 test casesLast 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.
- Text. Any run of characters outside tags is text and belongs to the innermost open element. Character entities (such as
&or<) are decoded the way Python'shtml.unescapedecodes them. - Comments.
<!--starts a comment that ends at the first following-->. Comments are ignored. An unterminated comment swallows the rest of the input. - 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. - 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. - 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/.
- If there is no
scriptandstyle. 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.- 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
markuphas length from 0 to about 10^5 and may be malformed in the ways described above.tag_nameis 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 & 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 & 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The work splits into two phases: build a tree, then query it.
Phase 1: build the tree in one pass. Walk the string with a position pointer and keep a stack of open elements, where the bottom is a synthetic document root. At each position, exactly one rule applies:
- Plain text becomes a text leaf under the stack top, with entities decoded.
- Comments and declarations are skipped.
- An end tag searches the stack from the top for the nearest open element with that name and pops down to it. A stray end tag with no match is ignored.
- A start tag creates an element under the stack top. It is pushed on the stack only if it is not void, not self-closing and not
script/style. Forscriptandstyle, the raw content up to the matching end tag is stored as one text leaf, with no decoding. - A
<that starts no valid construct becomes literal text, and a start tag with no>turns the rest of the input into text.
Phase 2: query with DFS. Using explicit stacks avoids recursion limits on deeply nested input.
- A post-order traversal computes each node's text as the concatenation of its children's text. Text leaves already hold their text.
- A pre-order traversal visits nodes in document order and collects the text of every element whose name equals the lowercase query. Pre-order puts an outer element before the elements nested inside it, which is the required order.
Why it is correct
Every character of input is consumed by exactly one rule, so each text run and element lands under the innermost still-open element at that point. Popping to the nearest matching open element implements the forgiving end-tag rule. Post-order guarantees that children's text exists before their parent needs it. Pre-order on a tree whose children are stored in input order yields the elements ordered by start-tag position.
Complexity
Parsing is linear in the input length, since each construct is scanned once and each stack element is pushed and popped at most once. The stack search for end tags can in the worst case cost the stack depth, so a pathological input with many unmatched end tags over a deep stack can be slower. Computing text is proportional to the total size of the strings built. When matching elements nest inside each other, each one's text is built separately, so the output size, and the time to build it, can grow quadratically with the nesting depth. Space is linear in the input plus the output size.
Reference solution
import re
from html import unescape
from typing import List
VOID_TAGS = {
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
'link', 'meta', 'param', 'source', 'track', 'wbr'
}
START_RE = re.compile(r'<\s*([A-Za-z][A-Za-z0-9:_-]*)')
END_RE = re.compile(r'</\s*([A-Za-z][A-Za-z0-9:_-]*)')
class Node:
__slots__ = ('tag', 'children', 'text')
def __init__(self, tag='', text=None):
self.tag = tag
self.children = []
self.text = text
def _parse(markup):
root = Node('#document')
stack = [root]
pos = 0
n = len(markup)
while pos < n:
if markup[pos] != '<':
end = markup.find('<', pos)
if end == -1:
end = n
stack[-1].children.append(Node(text=unescape(markup[pos:end])))
pos = end
continue
if markup.startswith('<!--', pos):
end = markup.find('-->', pos + 4)
pos = n if end == -1 else end + 3
continue
if markup.startswith('<!', pos) or markup.startswith('<?', pos):
end = markup.find('>', pos + 2)
pos = n if end == -1 else end + 1
continue
if markup.startswith('</', pos):
m = END_RE.match(markup, pos)
if m:
name = m.group(1).lower()
end = markup.find('>', m.end())
pos = n if end == -1 else end + 1
for i in range(len(stack) - 1, 0, -1):
if stack[i].tag == name:
del stack[i:]
break
continue
m = START_RE.match(markup, pos)
if m:
name = m.group(1).lower()
end = markup.find('>', m.end())
if end == -1:
stack[-1].children.append(Node(text=unescape(markup[pos:])))
break
raw = markup[m.end():end]
node = Node(tag=name)
stack[-1].children.append(node)
self_closing = raw.rstrip().endswith('/')
pos = end + 1
if name in ('script', 'style'):
close_re = re.compile(r'</\s*' + re.escape(name) + r'\s*>', re.I)
cm = close_re.search(markup, pos)
content_end = cm.start() if cm else n
if content_end > pos:
node.children.append(Node(text=markup[pos:content_end]))
pos = cm.end() if cm else n
elif name not in VOID_TAGS and not self_closing:
stack.append(node)
continue
stack[-1].children.append(Node(text='<'))
pos += 1
return root
def collect_tag_texts(markup: str, tag_name: str) -> List[str]:
root = _parse(markup)
target = tag_name.lower()
# Post-order pass: compute the text of every node.
text_of = {}
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if node.text is not None:
text_of[id(node)] = node.text
continue
if not visited:
stack.append((node, True))
for child in reversed(node.children):
stack.append((child, False))
else:
text_of[id(node)] = ''.join(text_of[id(c)] for c in node.children)
# Pre-order pass: report matching elements in document order.
result = []
stack = [root]
while stack:
node = stack.pop()
if node.text is None and node.tag == target:
result.append(text_of[id(node)])
stack.extend(reversed(node.children))
return result