python - 从 HTML 中删除标签,除了特定的标签(但保留它们的内容)
问题描述
我使用此代码删除 HTML 中的所有标记元素。我需要保持<br>
和<br/>
。所以我使用这段代码:
import re
MyString = 'aaa<p>Radio and<BR> television.<br></p><p>very<br/> popular in the world today.</p><p>Millions of people watch TV. </p><p>That’s because a radio is very small <span_style=":_black;">98.2%</span></p><p>and it‘s easy to carry. <span_style=":_black;">haha100%</span></p>bb'
MyString = re.sub('(?i)(<br\/?>)|<[^>]*>',r'\1', MyString)
print(MyString)
输出是:
aaaRadio and<BR> television.<br>very<br/> popular in the world today.Millions of people watch TV. That’s because a radio is very small 98.2%and it‘s easy to carry. haha100%bb
结果是对的,但现在我想保留<p>
and</p>
和<br>
and <br/>
。
如何修改我的代码?
解决方案
使用 HTML 解析器比使用正则表达式更健壮。正则表达式不应用于解析 HTML 等嵌套结构。
这是一个有效的实现,它遍历所有 HTML 标签,对于那些不是p
orbr
的人,将它们从标签中剥离:
from bs4 import BeautifulSoup
mystring = 'aaa<p>Radio and<BR> television.<br></p><p>very<br/> popular in the world today.</p><p>Millions of people watch TV. </p><p>That’s because a radio is very small <span_style=":_black;">98.2%</span></p><p>and it‘s easy to carry. <span_style=":_black;">haha100%</span></p>bb'
soup = BeautifulSoup(mystring,'html.parser')
for e in soup.find_all():
if e.name not in ['p','br']:
e.unwrap()
print(soup)
输出:
aaa<p>Radio and<br/> television.<br/></p><p>very<br> popular in the world today.</br></p><p>Millions of people watch TV. </p><p>That’s because a radio is very small 98.2%</p><p>and it‘s easy to carry. haha100%</p>bb
推荐阅读
- jquery - bootstrap 4将按钮放在上紧角
- asp.net-mvc - 与 ASP MVC 集成时,mdb-icon 在 Angular 中不起作用
- r - 无法弄清楚我的 R 函数代码中缺少什么 - 阻止它正常运行
- java - Swingutilities.invokeLater 和 while 循环
- php - FB分享按钮的URL中获取不同的APP key
- python-3.x - NLP 结构问题(进行特征提取的最佳方法)
- reactjs - ReactJS - 状态更改后重定向到私有路由
- java - 使用反射使用子类获取超类字段
- wordpress - 在订购产品后隐藏“添加到购物车”按钮 1 天,对于用户订购的产品
- .net - 在集成基于异步消息的系统中添加新服务的策略/框架是什么?