【问题标题】:Select HTML tags that have one or more specific attributes with bs4使用 bs4 选择具有一个或多个特定属性的 HTML 标记
【发布时间】:2016-06-16 06:14:08
【问题描述】:

我想使用soup.find_all 来查找所有具有idname 属性的HTML 标签。

以下代码适用于 id 属性:

for tag in soup.find_all(attrs={"id": True}):

但是,以下具有两个属性的代码却没有:

for tag in soup.find_all(attrs={"id":True, "name":True}):

是否可以使用 bs4 进行布尔搜索,以查找具有两个特定属性之一(或两个属性)的所有标签,还是我必须分别搜索每个属性?

【问题讨论】:

    标签: python html beautifulsoup attr


    【解决方案1】:
    soup.find_all(lambda element: 'name' in element.attrs or 'id' in element.attrs)
    

    我们使用lambda 来访问find_all 中的元素。然后,我们使用in 运算符来检查element.attrs(它是一个字典)是否有键name id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 2013-12-01
      • 2010-11-03
      • 2020-10-25
      • 2013-02-09
      • 2019-02-07
      相关资源
      最近更新 更多