본문 바로가기

개발 노트/Python

[Python] html entity decode 예제

반응형

개요

메일 등의 본문 내용 확인 시 간혹 "&#숫자;" 형태의 나열로 이루어진 스팸 메일이 있다.
이러한 형태는 HTML 에서 예약어로 사용하기 위해 별도로 만든 문자셋, 엔티티 (Entity) 라고 한다.
이러한 HTML Entity 는 Outlook 이나 일반 웹 페이지에서는 엔티티 형태의 데이터를 변환하여 사용자가 읽을 수 있는 문자열 형태로 보여주지만 데이터 그대로를 봤을 때는 개발자 입장에서는 이해할 수 없다.
따라서 이러한 HTML Entity 를 decoding 해주는 샘플을 정리한다.

아래 참고 링크에는 Web 에서 바로 사용할 수 있는 html entity encoder/decoder 를 첨부하였다. 필요 시 소스 없이 즉각변환이 가능하다.

예제

소스코드 (test.py)

# test.py
import re
import htmlentitydefs

entity_re = re.compile(r'&(%s|#(\d{1,5}|[xX]([\da-fA-F]{1,5})))[ ;]{0,1};' % '|'.join(htmlentitydefs.name2codepoint.keys()))

def html_entity_decode(s, encoding='ascii'):
    if not isinstance(s, basestring):
        raise TypeError('argument 1: expected string, %s found' % s.__class__.__name__)

    def entity_2_unichr(matchobj):
        g1, g2, g3 = matchobj.groups()
        if g3 is not None:
            codepoint = int(g3, 16)
        elif g2 is not None:
            codepoint = int(g2)
        else:
            codepoint = htmlentitydefs.name2codepoint[g1]
        return unichr(codepoint)

    if isinstance(s, unicode):
        entity_2_chr = entity_2_unichr
    else:
        entity_2_chr = lambda o: entity_2_unichr(o).encode(encoding, 'xmlcharrefreplace')
    def silent_entity_replace(matchobj):
        try:
            return entity_2_chr(matchobj)
        except ValueError:
            return matchobj.group(0)
    return entity_re.sub(silent_entity_replace, s)

print(html_entity_decode("안녕하세요", encoding='utf8'))

실행 결과

$ ./test.py
안녕하세요

참고 링크

 

HTML entity encoder/decoder

 

mothereff.in

반응형

'개발 노트 > Python' 카테고리의 다른 글

[Anaconda] _get_sat_solver_cls(57) 에러 조치  (0) 2020.12.06