Skip to main content
 首页 » 编程设计

python之BeautifulSoup find_all() 查找具有多个可接受属性值之一的元素

2025年05月04日9bluestorm

主要问题

我知道如何使用 find_all() 检索具有特定值属性的元素,但我找不到任何示例来说明如何检索具有多个可接受值之一的属性的元素。在我的例子中,我正在使用 DITA XML,我想检索范围属性为以下之一的 topicref 元素:

  • “同行”
  • “本地”
  • 无(属性不存在)

我编写了一个可用的自定义函数,但必须有一种更智能的方法来使用 BeautifulSoup 中已有的函数来执行此操作。这是我的代码:

from bs4 import BeautifulSoup 
 
with open("./dita_source/envvariables.ditamap","r") as file: 
    doc = BeautifulSoup(file) 
    file.close() 
 
 
def isLocal(element): 
    if (element.name == "topicref"): 
        if (not element.has_attr("scope") or element["scope"] == "local" or element["scope"] == "peer"): 
            return True; 
    return False; 
 
topicrefs = doc.find_all(isLocal) 

次要问题

有没有办法将 find_all() 与其标准过滤器和自定义函数一起使用?我尝试了 doc.find_all("topicref", isLocal),但这没有用。我不得不将额外的 if (element.name == "topicref"): 语句添加到我的自定义函数中。

请您参考如下方法:

您可以将列表作为属性参数的值提供给 find_all(),它将返回属性与该列表中的任何项目匹配的元素:

>>> soup.find_all(scope=["row", "col"]) 
[ 
    <th scope="col">US $</th>, 
    <th scope="col">Euro</th>, 
    <th scope="row">Mon – Fri</th>, 
    <th scope="row">Sat – Sun</th>, 
] 

...但是无法在该列表中指定“属性根本不存在”(None 和空字符串都不起作用)。因此,为此,您确实需要一个函数。