Bystroushaak / pyDHTMLParser

Lightweight HTML/XML parser for quick and dirty web scraping.
MIT License
6 stars 3 forks source link

Add insert_tag. #12

Open Bystroushaak opened 10 years ago

Bystroushaak commented 10 years ago
def insert_tag(tag, before, root):
    """
    Insert `tag` before `before` tag if present. If not, insert it into `root`.

    Args:
        tag (obj): HTMLElement instance.
        before (obj): HTMLElement instance.
        root (obj): HTMLElement instance.
    """
    if not before:
        root.childs.append(tag)
        tag.parent = root
        return

    before = before[0] if type(before) in [tuple, list] else before

    # put it before first existing identifier
    parent = before.parent
    iop = parent.childs.index(before)
    parent.childs.insert(
        iop,
        tag
    )