【问题标题】:How to find bs4 XML attribute values with BeautifulSoup by identifying attribute by regex in any XML depth?如何通过在任何 XML 深度中通过正则表达式识别属性来使用 BeautifulSoup 查找 bs4 XML 属性值?
【发布时间】:2021-08-17 03:02:04
【问题描述】:

我有以下 bs4 元素:

from bs4 import BeautifulSoup

html_doc = """
    <l2 attribute2="Output"><s3><Cell cell_value2="384.01"/></s3></l2>, 
    <l1><s3 attribute1="Cost"><s4><Cell cell_value1="2314.37"/></s4></s3></l1>
"""

soup = BeautifulSoup(html_doc, "html.parser")

我想像这样提取所有属性值:

["Output", "Cost"]

我的问题是:如何使用正则表达式re.compile(r'^attribute[0-9]$') 实现这一点,并且在attribute* 可以是第一个标签(例如l1l2)或者它可以是“更深”的情况下" 比如s3 或者其他任意深度)?

如果属性具有相同的名称,或者它们处于相同的深度级别但名称不同,我可以这样做 - 但不能两者兼而有之。

【问题讨论】:

    标签: python regex xml beautifulsoup


    【解决方案1】:
    import re
    from bs4 import BeautifulSoup
    
    html_doc = """
        <l2 attribute2="Output"><s3><Cell cell_value2="384.01"/></s3></l2>, 
        <l1><s3 attribute1="Cost"><s4><Cell cell_value1="2314.37"/></s4></s3></l1>
    """
    
    soup = BeautifulSoup(html_doc, "html.parser")
    
    r = re.compile(r"^attribute\d+")
    
    out = []
    for tag in soup.find_all(lambda tag: any(r.search(a) for a in tag.attrs)):
        for attr, value in tag.attrs.items():
            if r.search(attr):
                out.append(value)
    
    print(out)
    

    打印:

    ['Output', 'Cost']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多