【问题标题】:Python: Deleting all divs without classPython:删除所有没有类的div
【发布时间】:2020-06-13 20:55:11
【问题描述】:

我想删除所有没有类的 div(但不是 div 中的内容)。

我的意见

<h1>Test</h1>
<div>
    <div>
        <div class="test">
            <p>abc</p>
        </div>
    </div>
</div>

我想要的输出

<h1>Test</h1>
<div class="test">    
    <p>abc</p>
</div>

我的尝试 1

基于“Deleting a div with a particular class”:

from bs4 import BeautifulSoup
soup = BeautifulSoup('<h1>Test</h1><div><div><div class="test"><p>abc</p></div></div></div>', 'html.parser')   
for div in soup.find_all("div", {'class':''}): 
    div.decompose()
print(soup)
# <h1>Test</h1>

我的尝试 2

from htmllaundry import sanitize
myinput = '<h1>Test</h1><div><div><div class="test"><p>abc</p></div></div></div>'
myoutput = sanitize(myinput)
print myoutput
# <p>Test</p><p>abc</p> instead of <h1>Test</h1><div class="test"><p>abc</p></div>

我的尝试 3

基于“Clean up HTML in python

from lxml.html.clean import Cleaner

def sanitize(dirty_html):
    cleaner = Cleaner(remove_tags=('font', 'div'))

    return cleaner.clean_html(dirty_html)


myhtml = '<h1>Test</h1><div><div><div class="test"><p>abc</p></div></div></div>'

print(sanitize(myhtml))
# <div><h1>Test</h1><p>abc</p></div>

我的尝试 4

from html_sanitizer import Sanitizer
sanitizer = Sanitizer()  # default configuration
output = sanitizer.sanitize('<h1>Test</h1><div><div><div class="test"><p>abc</p></div></div></div>')
print(output)
# <h1>Test</h1><p>abc</p>

问题:div 元素用于为解析器包装 HTML 片段,因此不允许使用 div 标记。 (来源:Manual

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    如果要排除没有类的 div,保留其内容:

    from bs4 import BeautifulSoup
    markup = '<h1>Test</h1><div><div><div class="test"><p>abc</p></div></div></div>'
    soup = BeautifulSoup(markup,"html.parser")
    for tag in soup.find_all():
        empty = tag.name == 'div' and not(tag.has_attr('class'))
        if not(empty):
            print(tag)
    

    输出:

    <h1>Test</h1>
    <div class="test"><p>abc</p></div>
    <p>abc</p>
    

    【讨论】:

      【解决方案2】:

      请检查一下。

      from bs4 import BeautifulSoup
      
      data="""
      <div>
          <div>
              <div class="test">
                  <p>abc</p>
              </div>
          </div>
      </div>
      """
      soup = BeautifulSoup(data, features="html5lib")
      
      for div in soup.find_all("div", class_=True):
          print(div)
      
      

      【讨论】:

      • 脚本的输出是“abc abc”,而不是请求的“

        abc

        ”。
      猜你喜欢
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多