【问题标题】:How to Beautiful Soup (bs4) match just one, and only one, css classHow to Beautiful Soup (bs4) 只匹配一个,而且只有一个,css 类
【发布时间】:2020-08-09 04:52:43
【问题描述】:

我正在使用以下代码来匹配所有具有 CSS 类“ad_item”的 div。

soup.find_all('div',class_="ad_item")

我遇到的问题是,在该网页上,还有 div 的 CSS 类设置为“ad_ex_item”和“ad_ex_item”。

<div class="ad_item ad_ex_item">

In documentation it is stated:

当您搜索与某个 CSS 类匹配的标签时,您 匹配其任何 CSS 类:

那么我该如何匹配只有“ad_item”而没有“ad_ex_item”的div。

或者换句话说,如何搜索只有CSS类“ad_item”的div?

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

最佳答案是正确的,但如果您想要一种保持 for 循环清洁的方法或喜欢单行解决方案,请使用下面的列表理解。

data = [item for item in soup.find_all("div", class_="ad_item") if len(item["class"]) == 1] 

【讨论】:

    【解决方案2】:

    你可以像这样使用严格的条件:

    soup.select("div[class='ad_item']")
    

    用精确的类捕获div。 在这种情况下,只有 'ad_item' 没有其他空间类加入。

    【讨论】:

      【解决方案3】:

      您可以将 lambda 函数传递给 findfind_all 方法。

      soup.find_all(lambda x:
          x.name == 'div' and
          'ad_item' in x.get('class', []) and
          not 'ad_ex_item' in x['class']
      )
      

      对于没有class 属性的div 标签,x.get('class', []) 将避免KeyError 异常。

      如果您需要排除多个类,您可以将最后一个条件替换为:

          not any(c in x['class'] for c in {'ad_ex_item', 'another_class'})
      

      如果你想排除一些你可以使用的类:

         not all(c in x['class'] for c in {'ad_ex_item', 'another_class'})
      

      【讨论】:

        【解决方案4】:

        我找到了一个解决方案,虽然和BS4没有关系,但是是纯python代码。

        for item in soup.find_all('div',class_="ad_item"):
             if len(item["class"]) != 1:
                 continue;
        

        如果有多个 CSS 类,它基本上会跳过项目。

        【讨论】:

          【解决方案5】:

          您始终可以write a Python function that matches the tag you want,并将该函数传递给 find_all():

          def match(tag):
              return (
                  tag.name == 'div'
                  and 'ad_item' in tag.get('class')
                  and 'ad_ex_item' not in tag.get('class'))
          
          soup.find_all(match)
          

          【讨论】:

            【解决方案6】:

            您是否尝试过使用select : http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

            soup.select(".add_item")
            

            很遗憾,似乎不支持 CSS3 的 :not 选择器。如果你真的需要这个,你可能需要查看lxml。它似乎支持它。见http://packages.python.org/cssselect/#supported-selectors

            【讨论】:

              【解决方案7】:
              soup.fetch('div',{'class':'add_item'})
              

              【讨论】:

              • 我用的是Beautiful Soup 4,BS4没有fetch。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2021-05-09
              • 2020-12-16
              • 1970-01-01
              • 1970-01-01
              • 2015-03-14
              • 2017-05-07
              相关资源
              最近更新 更多