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

标签 python python-3.x beautifulsoup

主要问题

我知道如何使用 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/

相关文章:

python - PyScripter - 无法使用 KeyboardInterrupt 终止运行

python - sklearn 'preprocessor' 导入时子模块不可用

python - 使用 BeautifulSoup 直接从 HTML 中提取数据

image - 在 python 中使用 PIL 模糊图像

python - BeautifulSoup:打开本地和http html文件

python美汤提取数据

python - 使用pytest对学生代码进行测试和评分

python - 如何修复与 Postgres 的连接

python - 为什么 pygame.midi 不能在 Macos 上运行,而 pygame.mixer 可以

python - 如何在 Python collections.Counter 中执行 most_common 时忽略大小写?