[python] mathml이 포함된 html clean하게 하기

김준기·2024년 5월 25일
from lxml_html_clean import Cleaner

cleaner = Cleaner()

위 코드로 mathml이 포함된 html을 clean시키니 mathml도 같이 지워지는 문제가 발생했다.

찾아보니 Cleaner을 초기화 할 때 인자로 allow_tags로 허용할 태그를 확장하고 safe_attrs_onlyFalse로 설정하면 된다는 사실을 알았다.

아래는 mathml tag를 지우지 않도록 하는 코드다

> pip install lxml
> pip install lxml-html-clean
from lxml_html_clean import Cleaner
from lxml.html.defs import tags as BASIC_TAGS

MATHML_TAGS = frozenset(
    [
        "annotation", "annotation-xml", "merror", "mfrac",  "mi", 
        "mmultiscripts", "mn", "mo", "mover", "mpadded", 
        "mphantom", "mprescripts", "mroot", "mrow", "ms", 
        "semantics", "mspace", "msqrt", "mstyle", "msub", 
        "msup", "msubsup", "mtable", "mtd", "mtext", 
        "mtr", "munder", "munderover", 
    ]
)

ALL_ALLOW_TAG = BASIC_TAGS | MATHML_TAGS

cleaner = Cleaner(
    allow_tags=ALL_ALLOW_TAG,
    safe_attrs_only=False
)

참고로 cleaner을 사용할려면 clean_html 함수를 사용하면 된다.

profile
코딩 잘하고 싶은 백엔드 개발자

0개의 댓글