콘솔워크

파이썬 html str에 원하는 태그 삭제 (ex img 태그 제거) 본문

프로그래밍/python

파이썬 html str에 원하는 태그 삭제 (ex img 태그 제거)

콘솔워크 2022. 12. 10. 11:04
반응형

str 형태의 html 안에서 img 태그를 제거할 일이 생겼다

 

 

코드는 다음과 같다.

 

import re

def findtags(text):
    # make this non capturing group
    parms = '(?:\w+\s*=\s*"[^"]*"\s*)*'
    tags = "(<\s*\w+\s*" + parms + "\s*/?>)"
    return re.findall(tags, text)


def remove_img_tag_in_html(text: str):
    tags = findtags(text)
    for tag in tags:
        tag = str(tag)
        if tag.find("<img") > -1:
            text = text.replace(tag, "")
    print(text)

    return text

 

반응형