【问题标题】:decrease html headings using Python ElementTree使用 Python ElementTree 减少 html 标题
【发布时间】:2016-03-14 14:16:26
【问题描述】:

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

【问题讨论】:

    标签: python html xml elementtree


    【解决方案1】:

    这是一个工作示例,但使用了很棒的 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>
    

    【讨论】:

    • 感谢@alecxe。我试图避免使用外部库,例如 lxml 的美丽汤。但是,您的回答使我想到了如何使用 Etree 来做到这一点。我将在新答案中举个例子
    【解决方案2】:

    element.tag=newtag 可以解决问题。所需要做的就是为标题添加一个值。

    #! /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>
    <p>paragrap</p>
    '''
    
    tree = html5lib.parse(headings, namespaceHTMLElements=False)
    headings = [el for el in tree.findall('.//') if el.tag in ["h1","h2", "h3", "h4","h5","h6"]]
    
    for h in headings:
        newtag =  h.tag[0]+ str(int(h.tag[-1])+1)
        h.tag=newtag
    
    print ET.tostring(headings)
    

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 2012-12-13
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多