是否有一种递归方法可以使用 Python ElementTree 来减少 HTLM 树中的所有标题级别? 在下面的示例中,h1 将变为 h2,其他标题也是如此。
#! /usr/bin/env python
import html5lib
import xml.etree.ElementTree as ET
headings = '''<h1>Title</h1>
<h2>Sub Title</h2>
<h3>Sub sub title 1</h3>
<h3>Sub sub title 2</h3>
<h4>Sub sub sub title<h4>
<h3>Sub sub title</h3>
'''
tree = html5lib.parse(headings, namespaceHTMLElements=False)
最佳答案
这是一个工作示例,但使用了很棒的 BeautifulSoup
图书馆:
import re
from bs4 import BeautifulSoup
headings = '''<h1>Title</h1>
<h2>Sub Title</h2>
<h3>Sub sub title 1</h3>
<h3>Sub sub title 2</h3>
<h4>Sub sub sub title</h4>
<h3>Sub sub title</h3>
'''
soup = BeautifulSoup(headings, "html.parser")
pattern = re.compile(r"^h(\d)$")
for tag in soup.find_all(pattern):
tag.name = "h%d" % (int(pattern.match(tag.name).group(1)) + 1)
print(soup)
我们正在查找标签名称与 ^h(\d)$
模式匹配的所有元素(h
后跟一个数字;^
表示字符串的开头,$
- 结尾)。然后,我们提取数字并将其加一并更新标签名称。
打印:
<h2>Title</h2>
<h3>Sub Title</h3>
<h4>Sub sub title 1</h4>
<h4>Sub sub title 2</h4>
<h5>Sub sub sub title</h5>
<h4>Sub sub title</h4>
关于python - 使用 Python ElementTree 减少 html 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35989935/