from lxml.html.clean import Cleaner

try:
    from lxml_html_clean.clean import _find_external_links
except ImportError:
    # lxml 4
    from lxml.html.clean import _find_external_links


marker = []


class LaundryCleaner(Cleaner):
    link_target = marker

    def __call__(self, doc):
        super().__call__(doc)
        if self.link_target is not marker:
            self.force_link_target(doc, self.link_target)

    def force_link_target(self, doc, target):
        for el in _find_external_links(doc):
            if target is None:
                if "target" in el.attrib:
                    del el.attrib["target"]
            else:
                el.set("target", target)
