Python中的HTML截断
有没有一种纯Python工具,可以把一些HTML内容截断到尽量接近指定长度,并且确保截断后的内容是格式正确的?比如,给定以下HTML:
<h1>This is a header</h1>
<p>This is a paragraph</p>
它不应该生成:
<h1>This is a hea
而是应该生成:
<h1>This is a header</h1>
或者至少应该生成:
<h1>This is a hea</h1>
不过我找不到一个能正常工作的工具,虽然我发现了一个依赖于pullparser
的工具,但这个工具已经过时了,基本上算是死掉了。
8 个回答
5
我发现slacy的回答非常有帮助,如果我有足够的声望,我一定会给他点赞。不过还有一点需要注意。在我的环境中,我同时安装了html5lib和BeautifulSoup4。BeautifulSoup使用了html5lib这个解析器,这导致我的HTML片段被包裹在了html和body标签中,而这并不是我想要的结果。
>>> truncate_html("<p>sdfsdaf</p>", 4)
u'<html><head></head><body><p>s</p></body></html>'
为了解决这些问题,我告诉BeautifulSoup使用Python自带的解析器:
from bs4 import BeautifulSoup
def truncate_html(html, length):
return unicode(BeautifulSoup(html[:length], "html.parser"))
>>> truncate_html("<p>sdfsdaf</p>", 4)
u'<p>s</p>'
7
如果你在使用DJANGO这个库,你可以很简单地:
from django.utils import text, html
class class_name():
def trim_string(self, stringf, limit, offset = 0):
return stringf[offset:limit]
def trim_html_words(self, html, limit, offset = 0):
return text.truncate_html_words(html, limit)
def remove_html(self, htmls, tag, limit = 'all', offset = 0):
return html.strip_tags(htmls)
总之,这里是来自django的truncate_html_words的代码:
import re
def truncate_html_words(s, num):
"""
Truncates html to a certain number of words (not counting tags and comments).
Closes opened tags if they were correctly closed in the given html.
"""
length = int(num)
if length <= 0:
return ''
html4_singlets = ('br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input')
# Set up regular expressions
re_words = re.compile(r'&.*?;|<.*?>|([A-Za-z0-9][\w-]*)')
re_tag = re.compile(r'<(/)?([^ ]+?)(?: (/)| .*?)?>')
# Count non-HTML words and keep note of open tags
pos = 0
ellipsis_pos = 0
words = 0
open_tags = []
while words <= length:
m = re_words.search(s, pos)
if not m:
# Checked through whole string
break
pos = m.end(0)
if m.group(1):
# It's an actual non-HTML word
words += 1
if words == length:
ellipsis_pos = pos
continue
# Check for tag
tag = re_tag.match(m.group(0))
if not tag or ellipsis_pos:
# Don't worry about non tags or tags after our truncate point
continue
closing_tag, tagname, self_closing = tag.groups()
tagname = tagname.lower() # Element names are always case-insensitive
if self_closing or tagname in html4_singlets:
pass
elif closing_tag:
# Check for match in open tags list
try:
i = open_tags.index(tagname)
except ValueError:
pass
else:
# SGML: An end tag closes, back to the matching start tag, all unclosed intervening start tags with omitted end tags
open_tags = open_tags[i+1:]
else:
# Add it to the start of the open tags list
open_tags.insert(0, tagname)
if words <= length:
# Don't try to close tags if we don't need to truncate
return s
out = s[:ellipsis_pos] + ' ...'
# Close any tags still open
for tag in open_tags:
out += '</%s>' % tag
# Return string
return out
8
我觉得你不需要一个复杂的解析器——你只需要把输入的字符串分成以下几种部分:
- 文本
- 开始标签
- 结束标签
- 自闭合标签
- 字符实体
一旦你把这些部分分好,就可以用一个栈来跟踪哪些标签需要关闭。我之前遇到过这个问题,写了一个小库来解决它:
https://github.com/eentzel/htmltruncate.py
这个库对我来说效果很好,能处理大多数特殊情况,包括任意嵌套的标记、把字符实体算作一个字符、在标记格式错误时返回错误等等。
它会生成:
<h1>This is a hea</h1>
在你的例子中。这可能可以改变,但在一般情况下很难处理——比如说你想截断到10个字符,但<h1>
标签还要再300个字符才关闭,这该怎么办呢?