python - 从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 解析来删除。有没有办法做到这一点?我找到了这个库,但我找不到这样做的方法。在此先感谢。
解决方案
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
即使在文本中使用 ' > ' 或 ' < '这也会打印
推荐阅读
- python - 在 Matplotlib 中定义 GridSpec 的宽度/高度
- angular - 如何访问我在 Angular 7 中使用构造函数创建的对象数组
- javascript - 倾斜的 div 边框透明度
- java - 错误:找不到符号类 CouponBindingImpl
- reactjs - React Office Fabric UI - 节点模块无法自行解析
- ruby - Google App Engine 中的 Jekyll 应用程序抛出错误 502 Bad Gateway
- javascript - 如果语句不起作用 / Javascript / Jquery
- powershell - 使用 WebHook 将文件发送到 Microsoft Teams
- sql - 删除基于 30 天数据范围的归档数据
- javascript - React Redux:当道具改变时从 ACTION 重新加载组件