【问题标题】:Correctly parse empty html tags using beautiful soup使用漂亮的汤正确解析空的 html 标签
【发布时间】:2017-03-24 14:28:22
【问题描述】:

HTML 有一个空元素的概念,如MDN 中所列。然而,美丽的汤似乎并不能很好地处理它们:

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

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

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    正如他们在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 内容的原因。

    【讨论】:

    • 谢谢,需要注意的有用链接!
    【解决方案2】:

    我会说,soup 正在尽其所能来修复这个 html 结构,它实际上在某些情况下很有帮助。

    无论如何,对于您的情况,我会说使用lxml,它将根据您的需要解析html结构,或者尝试parsel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2019-11-10
      • 2013-03-21
      • 1970-01-01
      相关资源
      最近更新 更多