gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:38 26 4
gpt4 key购买 nike

主要问题

我知道如何使用 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 和空字符串都不起作用)。因此,为此,您确实需要一个函数。

关于python - BeautifulSoup find_all() 查找具有多个可接受属性值之一的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25830635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com