这似乎是一件简单的事情,但我一直找不到答案。我正在使用Pandoc将HTML转换为Markdown,我想要从HTML中删除所有属性,例如"class"和"id"。
Pandoc有没有这样的选项呢?
请考虑 input.html
文件:
<h1 class="test">Hi!</h1>
<p><strong id="another">This is a test.</strong></p>
pandoc input.html -t gfm-raw_html -o output.md
,生成output.md
文件。# Hi!
**This is a test.**
如果不使用-t gfm-raw_html
选项,您将得到以下结果:
# Hi! {#hi .test}
**This is a test.**
这个问题实际上类似于这个问题。我不认为pandoc会保留id
属性。
markdown_github-raw_html
已被弃用,因为 markdown_github
已被弃用,但您可以使用 gfm-raw_html
代替。 - Raymond Yeeremove-attr.lua
中,并使用 --lua-filter=remove-attr.lua
调用 pandoc。function remove_attr (x)
if x.attr then
x.attr = pandoc.Attr()
return x
end
end
return {{Inline = remove_attr, Block = remove_attr}}
<span style =“font-family:" Arial&quot;,sans-serif; color:black”> value </ span>
。 这与-t gfm-raw_html
一样有效。谢谢! - TheDudeAbides我也很惊讶这个看似简单的操作在网络搜索中没有产生任何结果。最终参考了BeautifulSoup文档和其他SO答案的示例使用方法,编写了以下代码。
下面的代码还会删除script
和style
HTML标签。除此之外,它将保留任何src
和href
属性。这两个属性应该可以让您灵活地适应您的需求(即适应任何需求,然后使用pandoc将返回的HTML转换为Markdown)。
# https://beautiful-soup-4.readthedocs.io/en/latest/#searching-the-tree
from bs4 import BeautifulSoup, NavigableString
def unstyle_html(html):
soup = BeautifulSoup(html, features="html.parser")
# remove all attributes except for `src` and `href`
for tag in soup.descendants:
keys = []
if not isinstance(tag, NavigableString):
for k in tag.attrs.keys():
if k not in ["src", "href"]:
keys.append(k)
for k in keys:
del tag[k]
# remove all script and style tags
for tag in soup.find_all(["script", "style"]):
tag.decompose()
# return html text
return soup.prettify()
pandoc -t markdown-header_attributes-link_attributes-native_divs-native_spans
等等... 或者,是的,编写一个 pandoc 过滤器。 - mb21