首页 > 解决方案 > 从python中的字符串中删除所有Html内容

问题描述

我想从字符串中删除所有 HTML 内容。

我有一个字符串

str= "I am happy with <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> 3333  <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> your code"

我想要最后的字符串 str= "I am happy with 3333 your code

我已经编写了这段代码来完成上述任务。

def removetags(input_str):
    result = ''
    startflag = 0
    start=True
    count=0
    for ch in input_str:
        if ch == '<':
            if count!=len(input_str)-1:
                if input_str[count+1]!='/':
                    start=True
                    startflag += 1


        elif (ch == '>') and startflag :
            if not start:
                startflag -= 1
            start=False

        elif (not startflag) :
            result += ch

        count += 1

    return result

print(removetags(str))

这很好用,但如果你<在文本中有一个,那么它将无法正确输出。所以我想使用 html 解析来删除。有没有办法做到这一点?我找到了这个库,但我找不到这样做的方法。在此先感谢。

标签: pythonhtmlparsingjirapreprocessor

解决方案


from html.parser import HTMLParser

str = "I am happy with <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> 3333 > <body> <h1>This is a Heading</h1>  <p>This is a paragraph.</p> </body> your code"

class MyHTMLParser(HTMLParser):
    got_html_in_tags = False
    html_free_text = []

    def handle_starttag(self, tag, attrs):
        self.got_html_in_tags = True

    def handle_endtag(self, tag):
        self.got_html_in_tags = False

    def handle_data(self, data):
        if not self.got_html_in_tags:
            self.html_free_text.append(data)


parser = MyHTMLParser()
parser.feed(str)
print("".join(parser.html_free_text))

I am happy with 3333 your code即使在文本中使用 ' > ' 或 ' < '这也会打印


推荐阅读