【问题标题】:Extract content of div tag except other tags using BeuatifulSoup使用 BeautifulSoup 提取除其他标签外的 div 标签内容
【发布时间】:2020-11-17 13:46:02
【问题描述】:

我有以下 HTML 内容,其中 div 标签如下所示

<div class="block">aaa
 <p> bbb</p>
 <p> ccc</p>
</div>

从上面我想只提取文本为“aaa”而不是其他标签内容。

当我这样做时,

 soup.find('div', {"class": "block"})

它将所有内容作为文本提供给我,我想避免 p 标签的内容。

BeautifulSoup 中是否有可用的方法来执行此操作?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    检查元素的类型,你可以试试:

    from bs4 import BeautifulSoup
    from bs4 import element
    
    s = '''
    <div class="block">aaa
     <p> bbb</p>
     <p> ccc</p>
     <h1>ddd</h1>
    </div>
    '''
    
    soup = BeautifulSoup(s, "lxml")
    for e in soup.find('div', {"class": "block"}):
        if type(e) == element.NavigableString and e.strip():
            print(e.strip())
    # aaa
    

    这将忽略子标签中的所有文本。

    【讨论】:

      【解决方案2】:

      您可以从div 中删除p 标记,这样可以有效地为您提供aaa 文本。

      方法如下:

      from bs4 import BeautifulSoup
      
      sample = """<div class="block">aaa
       <p> bbb</p>
       <p> ccc</p>
      </div>
      """
      
      s = BeautifulSoup(sample, "html.parser")
      excluded = [i.extract() for i in s.find("div", class_="block").find_all("p")]
      print(s.text.strip())
      

      输出:

      aaa
      

      【讨论】:

        【解决方案3】:

        您可以使用find_next(),它返回找到的第一个匹配项:

        from bs4 import BeautifulSoup
        
        html = '''
        <div class="block">aaa
         <p> bbb</p>
         <p> ccc</p>
        </div>
        '''
        
        soup = BeautifulSoup(html, "html.parser")
        
        print(soup.find('div', {"class": "block"}).find_next(text=True))
        

        输出:

        aaa
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-25
          • 1970-01-01
          • 2019-05-11
          • 1970-01-01
          • 2015-10-22
          • 1970-01-01
          • 2012-02-13
          • 1970-01-01
          相关资源
          最近更新 更多