BeautifulSoup 在遇到没有伴随打开标签的结束标签时过早切断 div

BeautifulSoup prematurely cutting off div when encountering a closing tag without an accompanying open tag

我遇到了与 this question 的提问者类似的问题,但该问题从未收到 Python 3.

的回复

我正在尝试抓取一个经常在 div 中间使用自定义结束标记的页面,而我正在寻找没有随附的开始标记,这导致 BeautifulSoup将其视为 div.

的结尾

HTML 看起来像...

<div class="eligible-promo">
    <h4>Promo Header</h4>
    <ul>
        <li>items here</li>
    </ul>
    <ul>
        <li>item here</li>
    </ul>

    </productlist:g047:g0471>

    <h4>Different Promo Header</h4>
    <ul>
        <li>items here</li>
    </ul>
    <ul>
        <li>item here</li>
    </ul>

    </productlist:g047:g0472>

</div>

当我运行soup.find('div', {'class': 'eligible-promo'}),BeautifulSoup回来的时候...

<div class="eligible-promo">
    <h4>Promo Header</h4>
    <ul>
        <li>items here</li>
    </ul>
    <ul>
        <li>item here</li>
    </ul>
</div>

这个 HTML 不是我写的,我不知道 </productlist> 标签是什么,也不知道为什么它没有伴随的开始标签。我所知道的是 BeautifulSoup 正在用 </div> 标签替换它,但我不想这样。我正在使用 Python 3.8.1 版和 BeautifulSoup 4.8.2 版。

再想想,我想你想要的是 find_all() 而不是 find() 因为 运行 这个:

from bs4 import BeautifulSoup

sample = """
<div class="eligible-promo">
    <h4>Promo Header</h4>
    <ul>
        <li>items here</li>
    </ul>
    <ul>
        <li>item here</li>
    </ul>

    </productlist:g047:g0471>

    <h4>Different Promo Header</h4>
    <ul>
        <li>items here</li>
    </ul>
    <ul>
        <li>item here</li>
    </ul>

    </productlist:g047:g0472>

</div>
"""

soup = BeautifulSoup(sample, "html.parser").find_all("div", {"class": "eligible-promo"})
print(soup)

给出这个:

[<div class="eligible-promo">
<h4>Promo Header</h4>
<ul>
<li>items here</li>
</ul>
<ul>
<li>item here</li>
</ul>

<h4>Different Promo Header</h4>
<ul>
<li>items here</li>
</ul>
<ul>
<li>item here</li>
</ul>

</div>]

因此,div 中包含所有标签。无需担心这种不需要关闭的 scary void 元素singelton 标签标签有效。

这些元素通常是在页面上独立存在的元素,或者从页面本身的上下文中可以明显看出其内容结尾的元素。

HTML 中有很多。喜欢<img>,例如...

编辑:

我已经安装了您的 BeautifulSoup == 4.8.2 版本,现在我可以重现该问题。我想,是时候升级了。该代码在版本 4.9.3.

中按预期工作