首页 > 解决方案 > 如何通过在任何 XML 深度中通过正则表达式识别属性来使用 BeautifulSoup 查找 bs4 XML 属性值?

问题描述

我有以下 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或其他任意深度)的情况下?

如果属性具有相同的名称,或者它们位于具有不同名称的相同深度级别,我可以执行此操作 - 但不能两者兼而有之。

标签: pythonregexxmlbeautifulsoup

解决方案


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']

推荐阅读