我有一个使用 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 写入文件时是否可以保留原始文件的空白?
最佳答案
虽然这是一个 hack,但我发现的最干净的方法是猴子补丁 BeautifulSoup.pushTag
:
#!/usr/bin/env python
from bs4 import BeautifulSoup
pushTag = BeautifulSoup.pushTag
def myPushTag(self, tag):
pushTag(self, tag)
self.preserve_whitespace_tag_stack.append(tag)
BeautifulSoup.pushTag = myPushTag
在 BeautifulSoup 中,pushTag
将某些标签(只是 pre
和 textarea
in beautifulsoup4)附加到 preserve_whitespace_tag_stack
。这个猴子补丁只是覆盖了那个行为,所以 所有 标签最终都在 preserve_whitespace_tag_stack
中。
我强烈建议您在使用时谨慎行事,因为这可能会产生意想不到的后果。
关于python - 使用 BeautifulSoup 写入文件时在 Django 模板中保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054116/