【问题标题】:How to prevent BeautifulSoup from adding extra doctype entry如何防止 BeautifulSoup 添加额外的文档类型条目
【发布时间】:2022-09-30 12:21:10
【问题描述】:

如果我读取一个 html 文件并用 bs4 加载它,我会得到一个额外的 doctype 条目。我该如何预防?

HTML 代码

<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">
<html>
<body>
<p>
text body
</p>
</body>
</html>

这就是文件的处理方式

from bs4 import BeautifulSoup

page = urllib.urlopen(file_name).read()
page_soup = BeautifulSoup(page, \'html.parser\')

生成的 HTML

<!DOCTYPE doctype html public \"-//w3c//dtd html 4.0 transitional//en\">
<html>
<body>
<p>
text body
</p>
</body>
</html>

    标签: python beautifulsoup


    【解决方案1】:

    也许问题不在于 BS,因为我无法重现该问题。

    运行这个

    from bs4 import BeautifulSoup
    import urllib.request
    
    
    file_name = 'file:///C:/Users/tang/MathScripts/t.html'
    page = urllib.request.urlopen(file_name).read()
    soup = BeautifulSoup(page, 'html.parser')
    print(soup)
    

    我明白了

    <!DOCTYPE html public "-//w3c//dtd html 4.0 transitional//en">
    
    <html>
    <body>
    <p>
    text body
    </p>
    </body>
    </html>
    

    【讨论】:

    • 我在这个问题上花了一些时间,并了解到如果“!DOCTYPE”是用小案例“!doctype”编写的,这个问题会重现。我不太确定这是否是设计使然。你怎么看?
    【解决方案2】:

    看起来 doctype 字符串在 HTML 规范中不区分大小写,但在 XML 规范中区分大小写。

    这在post: "Uppercase or lowercase doctype?" 中有很好的解释。

    根据这些信息,我认为 BeautifulSoup 没有正确处理 html doctype 字符串。

    我改变了我的代码如下,它现在工作正常。

    page = urllib.urlopen(file_name).read()
    # case insensitive replace to consider all case permutations
    page = re.sub('<!doctype', '<!DOCTYPE', page, flags=re.IGNORECASE)
    page_soup = BeautifulSoup(page, 'html.parser')
    

    我不太确定 html 规范是否已更新。

    如果您有更多信息要分享,请发表评论。

    【讨论】:

      【解决方案3】:

      又找到了一个解决方案。

      我用 'html5lib' 替换了 'html.parser' ,它工作正常。

      page = urllib.urlopen(file_name).read()
      page_soup = BeautifulSoup(page, 'html5lib')
      

      【讨论】:

        猜你喜欢
        • 2014-08-15
        • 2021-08-24
        • 2013-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-26
        相关资源
        最近更新 更多