python - 使用 Python ElementTree 减少 html 标题

标签 python html xml elementtree

是否有一种递归方法可以使用 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/

相关文章:

python - 使用图形 View 小部件显示图像

Python 和异步 : closed named pipe always available for reading

python - 验证和登录之间有什么区别?

javascript - 在不从顶部计算的情况下淡入单个页面上的div

android - LaTeX 或 MathML 到 Android 上的图像

java - 安卓 :xml file not working

xml - axis step child::element 不能在这里使用:上下文项是一个原子值

python - Keras 代码 Q-learning OpenAI gym FrozenLake 有问题

html - 在 HTML5 的表格标题中使用按钮在语义上是否正确?

html - CSS 渐变边框显示不正确