【问题标题】:How to Find a tag without specific attribute using beautifulsoup?如何使用 beautifulsoup 查找没有特定属性的标签?
【发布时间】:2019-01-12 19:10:10
【问题描述】:

我正在尝试获取没有特定属性的“p”标签的内容。

我有一些带有 'class'='cost' 的标签,还有一些带有 'class'='cost' 和 'itemprop'='price' 的标签

all_cars = soup.find_all('div', attrs={'class': 'listdata'})
...
...
tatal_cost= car.findChildren('p', attrs={'class': 'cost'})
cost= car.findChildren('p', attrs={'class': 'cost', 'itemprop':'price'})

我正在尝试查找没有“itemprop”属性的“p”标签,但找不到任何解决方案。

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    BeautifulSoup 内置的属性过滤器就足够了。您可以将True 作为值来简单检查该属性是否存在。 None 可用于指定该属性不应存在。同样,该值可以是任何属性值(例如“成本”)。

    from bs4 import BeautifulSoup
    html="""
    <p class="cost">paragraph 1</p>
    <p class="cost">paragraph 2</p>
    <p class="cost">paragraph 3</p>
    <p class="cost" itemprop="1">paragraph 4</p>
    <p class="somethingelse">paragraph 5</p>
    """
    soup=BeautifulSoup(html,'html.parser')
    print("---without 'itemprop' attribute")
    print(soup.find_all('p',itemprop=None))
    print("---with class = 'cost' and without 'itemprop' attribute----")
    print(soup.find_all('p',attrs={'itemprop':None,"class":'cost'}))
    #below is an alternative way to specify this
    #print(soup.find_all('p',itemprop=None,class_='cost'))
    

    输出

    ---without 'itemprop' attribute
    [<p class="cost">paragraph 1</p>, <p class="cost">paragraph 2</p>, <p class="cost">paragraph 3</p>, <p class="somethingelse">paragraph 5</p>]
    ---with class = 'cost' and without 'itemprop' attribute----
    [<p class="cost">paragraph 1</p>, <p class="cost">paragraph 2</p>, <p class="cost">paragraph 3</p>]
    

    【讨论】:

      【解决方案2】:

      BeautifulSoup 允许您定义一个函数并将其传递给它的find_all() 方法:

      def has_class_but_not_itemprop(tag):
          return tag.has_attr('class') and not tag.has_attr('itemprop')
      
      # Pass this function into find_all() and you’ll pick up all the <p> 
      # tags you're after:
      
      soup.find_all(has_class_but_not_itemprop)
      # [<p class="cost">...</p>,
      #  <p class="cost">...</p>,
      #  <p class="cost">...</p>]
      

      有关详细信息,请参阅BeautifulSoup documentation

      【讨论】:

      • 我认为这样做比使用soup.find_all('p', attrs={'class': 'cost', 'itemprop':None}) 或等效的soup.find_all('p', class_='cost', itemprop=None) 没有任何好处——有吗? (显然该函数更灵活,非常适合依赖,但匹配None 比该函数更简单 基准测试。)编辑:我刚刚注意到它是Bitto Bennichan’s answer 下面。跨度>
      猜你喜欢
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 2012-02-14
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      相关资源
      最近更新 更多