Strip whitespace in generated HTML using pure Python code

大城市里の小女人 提交于 2019-12-05 03:56:57

If you just want to get rid of excess whitespace, you can use:

>>> import re
>>> html_string = re.sub(r'\s\s+', ' ', html_string)

or:

>>> html_string = ' '.join(html_string.split())

If you want to do something more complicated than just stripping excess whitespace, you'll need to use more powerful tools (or more complex regexps).

You might also investigate Jinja's built-in whitespace control, which might alleviate some of the need for manually removing whitespace after your templates have been rendered.

Quoting the docs:

But you can also strip whitespace in templates by hand. If you put an minus sign (-) to the start or end of an block (for example a for tag), a comment or variable expression you can remove the whitespaces after or before that block:

{% for item in seq -%}
    {{ item }}
{%- endfor %}

This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9 the output would be 123456789.

I found python slimmer library, perfect for what you need to do.

from slimmer import html_slimmer # or xhtml_slimmer, css_slimmer
html = html_slimmer(html)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!