gpt4 book ai didi

python - 使用美汤正确解析空html标签

转载 作者:行者123 更新时间:2023-11-28 04:46:42 25 4
gpt4 key购买 nike

HTML 有空元素的概念,如 MDN 中所列.然而, BeautifulSoup 似乎并不能妥善处理它们:

import bs4

soup = bs4.BeautifulSoup(
'<div><input name=the-input><label for=the-input>My label</label></div>',
'html.parser'
)
print(soup.contents)

我得到:

[<div><input name="the-input"><label for="the-input">My label</label></input></div>]

即输入已经包裹了标签。

问题:有什么办法可以得到漂亮的汤来正确解析这个?还是我还没有找到对这种行为的官方解释?

至少我希望是这样的:

[<div><input name="the-input"></input><label for="the-input">My label</label></div>]

即输入在标签之前自动关闭。

最佳答案

如他们的 documentation 所述html5lib 像 Web 浏览器一样解析文档(在这种情况下就像 lxml)。它会在需要时尝试通过添加/关闭标签来修复您的文档树。

在您的示例中,我使用 lxml 作为解析器,它给出了以下结果:

soup = bs4.BeautifulSoup(
'<div><input name=the-input><label for=the-input>My label</label></div>',
'lxml'
)
print(soup.body.contents)

[<div><input name="the-input"/><label for="the-input">My label</label></div>]

请注意,lxml 添加了 html 和 body 标签,因为它们在源代码中不存在,这就是我打印 body 内容的原因。

关于python - 使用美汤正确解析空html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43002091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com