【发布时间】:2018-10-07 19:26:39
【问题描述】:
我有一个脚本,它使用 Beautiful Soup 向标题标签添加类。
#!/usr/bin/env python
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('test.html'), 'html.parser')
heading_tags = soup.find_all('h1')
for tag in heading_tags:
tag['class'].append('new-class')
with open('test.html', 'w') as html_doc:
html_doc.write(soup.prettify())
这很好用,但我想在写入文件时保留文件中的空格。例如,这个 Django 模板:
<div class="something">
<div class="else">
<h1 class="original-class">Test</h1>
{% if request.foo == 'bar' %}
{{ line.get_something }}
{% else %}
{{ line.get_something_else }}
</div>
</div>
变成:
<div class="something">
<div class="else">
<h1 class="original-class new-class">
Test
</h1>
<!-- The formatting is off here: -->
{% if request.foo == 'bar' %}
{{ line.get_something }}
{% else %}
{{ line.get_something_else }}
</div>
</div>
我也尝试使用soup.encode() 而不是soup.prettify()。这保留了 Django 模板代码,但扁平化了 HTML 结构。
使用 Beautiful Soup 写入文件时是否可以保留原始文件的空白?
【问题讨论】:
-
这可能会有所帮助:stackoverflow.com/a/15513483/7832176
标签: python html beautifulsoup django-templates whitespace