【问题标题】:Preserve Whitespace in Django Template When Writing to a File With BeautifulSoup使用 BeautifulSoup 写入文件时在 Django 模板中保留空格
【发布时间】: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 写入文件时是否可以保留原始文件的空白?

【问题讨论】:

标签: python html beautifulsoup django-templates whitespace


【解决方案1】:

虽然这是一个 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 将某些标签(在 beautifulsoup4 中只是 pretextarea)附加到 preserve_whitespace_tag_stack。这个猴子补丁只是覆盖了这种行为,因此 all 标记最终出现在 preserve_whitespace_tag_stack

请谨慎使用,因为可能会产生意想不到的后果。

【讨论】:

    猜你喜欢
    • 2011-12-09
    • 2019-04-15
    • 2012-06-29
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    相关资源
    最近更新 更多