python - 如何通过在任何 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*
第一个标签(例如l1
或l2
)上的情况或者它可以是“更深”(例如在s3
或其他任意深度)的情况下?
如果属性具有相同的名称,或者它们位于具有不同名称的相同深度级别,我可以执行此操作 - 但不能两者兼而有之。
解决方案
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']
推荐阅读
- python - Facebook 图表:帖子未显示给 Facebook 主页粉丝
- flutter - Flutter 中调用 Future 和 Future.microtask 有什么区别?
- php - PHP函数被调用但不带参数
- jira - JQL:当父级移动到“完成”时隐藏“完成”子任务
- javascript - kendoMultiSelect:Java Selenium 如何选择多个值?
- javascript - 如何在 JS 中过滤 JSON 数据
- php - 在查询结果或查询比较中包含列名
- ruby-on-rails-5.2 - 按常用列关联关闭 3 个模型
- javascript - AngularJS ng-repeat orderBy / filter:在一种情况下调用后端的函数,在其他情况下在前端排序
- javascript - JavaScript 变量作用域