python - 使用 BeautifulSoup 写入文件时在 Django 模板中保留空格

标签 python html beautifulsoup django-templates whitespace

我有一个使用 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 将某些标签(只是 pretextarea in beautifulsoup4)附加到 preserve_whitespace_tag_stack。这个猴子补丁只是覆盖了那个行为,所以 所有 标签最终都在 preserve_whitespace_tag_stack 中。

我强烈建议您在使用时谨慎行事,因为这可能会产生意想不到的后果。

关于python - 使用 BeautifulSoup 写入文件时在 Django 模板中保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054116/

相关文章:

python - 在并发请求的情况下,将数据存储在 Django 应用程序中的 "thread local storage"中是否安全?

python - 如何开始开发 python IDLE 扩展?

python - 迷惑Gothon练习游戏Python

javascript - 将 2 列与容器对齐

php - 通过表单更新中的 POST 方法传递表单值

python - Django manage.py 未知命令 : 'syncdb'

html - 如何将 CSS 应用于 iOS NSAttributedString

Python - BeautifulSoup - 通过列表中的特定元素遍历 findall

python - BS4 中出现奇怪的错误。 find_all() 返回 None

python - BeautifulSoup 处理多个 .html 文件