Python 在LXML中,如何保留标记,但删除所有内联样式等?
我知道我可以用LXML删除标签,如Python 在LXML中,如何保留标记,但删除所有内联样式等?,python,html,lxml,lxml.html,Python,Html,Lxml,Lxml.html,我知道我可以用LXML删除标签,如等,但如何让它保留标签,同时删除其他所有内容,如: <h1 style='font-size: 24px; margin: 0px 0px 12px; font-weight: 600; line-height: 28px; color: rgb(23, 43, 77); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Rob
等,但如何让它保留标签,同时删除其他所有内容,如:
<h1 style='font-size: 24px; margin: 0px 0px 12px; font-weight: 600;
line-height: 28px; color: rgb(23, 43, 77); font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Noto Sans", Ubuntu, "Droid Sans",
"Helvetica Neue", sans-serif; font-style: normal;
font-variant-ligatures: normal; font-variant-caps: normal;
letter-spacing: normal; orphans: 2; text-align: start;
text-indent: 0px; text-transform: none; white-space: normal;
widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;
background-color: rgb(244, 245, 247); text-decoration-style:
initial; text-decoration-color: initial;'>This text must stay</h1>
你说的“标签类”是什么意思?你的样本中没有类。你是对的,我没有包括那个样本。一些未包含的数据中包含了类信息,但我怀疑这个想法很清楚。我想要标签,里面没有类、样式等任何东西。如果样本更具代表性,想法会更清晰。问题是什么并不明显。这是公平的,更多的例子会更好。我相信问题的这一部分展示了一个例子h1和所有的数据,然后展示了它在
之后需要的样子。这篇文章必须保持基本上说明了需要什么。
safe_attrs = list(lxml.html.clean.defs.safe_attrs) + ['bgcolor']
lxml.html.clean.defs.safe_attrs = safe_attrs
lxml.html.clean.Cleaner.safe_attrs = lxml.html.clean.defs.safe_attrs
cleaner = lxml.html.clean.Cleaner(style=False, remove_tags=['body', 'pre'], safe_attrs_only=True,
safe_attrs=safe_attrs, kill_tags=['title', 'code'])
return cleaner.clean_html(data)