Python:删除没有类的所有div

Python:删除没有类的所有div,python,beautifulsoup,Python,Beautifulsoup,我想删除所有没有类的div,但不删除div中的内容 我的意见 我想要的输出 我的尝试1 基于: 我的尝试2 我的第三次尝试 基于 我的第四次尝试 问题:div元素用于为解析器包装HTML片段,因此不允许使用div标记。来源:请签出此项 from bs4 import BeautifulSoup data=""" <div> <div> <div class="test"> <p>abc</p&

我想删除所有没有类的div,但不删除div中的内容

我的意见

我想要的输出

我的尝试1

基于:

我的尝试2

我的第三次尝试

基于

我的第四次尝试

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

请签出此项

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)


如果要排除没有类的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>

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

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>
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>
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>
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)

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>