【问题标题】:How to get all the tags (with content) under a certain class with BeautifulSoup?如何使用 BeautifulSoup 获取某个类下的所有标签(带有内容)?
【发布时间】:2021-05-20 00:20:02
【问题描述】:

我的汤元素中有一个类,它是一个单元的描述。

<div class="ats-description">
 <p>Here is a paragraph</p>
 <div>inner div</div>
 <div>Another div</div>
 <ul>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
 </ul>
</div>

我可以通过soup.select(".ats-description")[0] 轻松获取这部分内容。 现在我想删除&lt;div class="ats-description"&gt;,只保留所有内部标签(保留文本结构)。怎么做?

soup.select(".ats-description")[0].getText() 给了我里面的所有文字,像这样:

'\nHere is a paragraph\ninner div\nAnother div\n\nItem1\nItem2\nItem3\n\n\n'

但是删除了所有内部标签,所以它只是非结构化文本。我也想保留标签。

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    要获取innerHTML,使用方法.decode_contents()

    innerHTML = soup.select_one('.ats-description').decode_contents()
    print(innerHTML)
    

    【讨论】:

      【解决方案2】:

      试试这个,按soup.find_all()列表中的标签匹配

      from bs4 import BeautifulSoup
      
      html="""<div class="ats-description">
       <p>Here is a paragraph</p>
       <div>inner div</div>
       <div>Another div</div>
       <ul>
          <li>Item1</li>
          <li>Item2</li>
          <li>Item3</li>
       </ul>
      </div>"""
      
      soup = BeautifulSoup(html, 'lxml')
      print(soup.select_one("div.ats-description").find_all(['p','div','ul']))
      

      【讨论】:

      • 我不知道里面会有什么。所以,我不能像你那样对所有标签进行硬编码。它可能有效,也可能无效。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多