【问题标题】:Why does BeautifulSoup remove all the formatting from my HTML?为什么 BeautifulSoup 会从我的 HTML 中删除所有格式?
【发布时间】:2020-05-16 03:04:54
【问题描述】:

我有一个 HTML 文件,看起来或多或少像

<body>
    <div>
        <aside class="bg">
            <a href="index.html">Home</a>
        </aside>
    </div>
</body>

但是在我用 BeautifulSoup 解析它然后将它写入文件之后,我所有的格式都消失了。我的代码如下:

with open('contact.html', 'r') as f:
    soup = BeautifulSoup(f, "html.parser")
elem = soup.find("aside")
new_html = "<a href="support.html">Support</a>"
new_soup = BeautifulSoup(new_html, "html.parser")
elem.insert(1, newsoup)
with open('contact.html', 'w') as f:
    f.write(str(soup))

生成的 html 文件如下所示

<body>
<div>
<aside class="bg">
<a href="support.html">Support</a>
<a href="index.html">Home</a>
</aside>
</div>
</body>

我不想使用 prettify,因为我不喜欢它的格式。我只想保持我的格式不变。有什么办法可以做到吗?

【问题讨论】:

  • 如果您将已解析的 HTML 作为元素树进行编辑,它应该如何知道如何“保持格式不变”?特别是它应该如何决定插入的元素缩进多少?
  • 我猜soup.prettify() 是我唯一的选择,我必须接受它提供的格式。

标签: python html beautifulsoup


【解决方案1】:

这个帖子里有讨论

Maintaining the indentation of an XML file when parsed with Beautifulsoup

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2016-06-24
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2020-08-11
    • 1970-01-01
    • 2016-12-09
    相关资源
    最近更新 更多