首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何找到具有这些属性的所有元素?

如何找到具有这些属性的所有元素?
EN

Stack Overflow用户
提问于 2021-04-08 18:23:19
回答 2查看 37关注 0票数 0

看看这些标签和它们的属性:link

代码语言:javascript
复制
</tr> <tr data-has-trading-incentive="false" data-is-centralized="true">

</tr> <tr data-has-trading-incentive="false" data-is-centralized="true">   </tr> <tr data-is-centralized="true">

</tr> <tr data-has-trading-incentive="true">

</tr> <tr data-has-trading-incentive="false" data-is-centralized="false"> </tr> <tr data-has-trading-incentive="false">

我想用python中的Beautifulsoup找到所有带有"tr“标签和属性的元素,就像下面的任何一个。

下面是我正在做的事情

代码语言:javascript
复制
soup.findAll("tr",attrs={re.compile("(data\-is\-centralized|data\-has\-trading-incentive)"):re.compile("(true|false)")})

但这不会返回任何值。我做错了什么?有没有更好的方法来做这件事?

EN

回答 2

Stack Overflow用户

发布于 2021-04-08 18:53:23

您可以使用css OR语法对任一属性进行匹配

代码语言:javascript
复制
soup.select('[data-has-trading-incentive], [data-is-centralized]')
票数 1
EN

Stack Overflow用户

发布于 2021-04-08 18:35:28

find_all也接受函数,其中函数默认将每个element作为其属性。

试试这个:

代码语言:javascript
复制
def findFilter(element):
    if element.name == "tr":
        if any(attr in list(element.attrs.values()) for attr in ['data-has-trading-incentive','data-is-centralized']):
            return True
    return False


filteredElements = soup.find_all(findFilter)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67002025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档