使用Python删除部分HTML文本

2024-04-25 23:04:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常长的HTML文本,其结构如下:

<div>
    <div>
        <p>Paragraph 1 Lorem ipsum dolor... long text... </p>
        <p>Paragraph 2 Lorem ipsum dolor... long text... </p>
        <p>Paragraph 3 Lorem ipsum dolor... long text... </p>
    </div>
</div>

现在,假设我想将HTML文本修剪为1000个字符,但是我仍然希望HTML是有效的,也就是说,关闭那些关闭标记被删除的标记。如何使用Python更正修剪过的HTML文本?请注意,HTML的结构并不总是如上所述。你知道吗

我需要一个电子邮件活动,其中的博客预览发送,但收件人需要访问博客的网址来查看完整的文章。你知道吗


Tags: text标记文本div电子邮件html结构收件人
2条回答

我可以举个例子。 如果是这样:

<div> <p>Long text...</p> <p>Longer text to be trimmed</p> </div>

你的Python代码如下:

def TrimHTML(HtmlString):
    result = []
    newlinesremaining = 2 # or some other value of your choice
    foundlastpart = False
    for x in list(HtmlString): # being HtmlString the html to be trimmed
        if not newlinesremaining < 1:
            if x == '\n':
                newlinesremaining -= 1
            result.append(x)
        elif foundlastpart == False:
            if x == \n:
                newlinesremaining = float('inf')
                foundlastpart == True
        return result.join('')

在函数中输入上面的HTML示例,然后函数返回:

出于某种奇怪的原因,我无法在工作前的短时间内测试它。你知道吗

美女团怎么样?(python-bs4)

from bs4 import BeautifulSoup

test_html = """<div>
    <div>
        <p>Paragraph 1 Lorem ipsum dolor... long text... </p>
        <p>Paragraph 2 Lorem ipsum dolor... long text... </p>
        <p>Paragraph 3 Lorem ipsum dolor... long text... </p>
    </div>
</div>"""

test_html = test_html[0:50]
soup = BeautifulSoup(test_html, 'html.parser')

print(soup.prettify())

.prettify()应自动关闭标记。你知道吗

相关问题 更多 >