首页 > 解决方案 > 如何使用beautifulsoup python从HTML页面中提取原始文本(包括评论)?

问题描述

假设我有以下 HTML:

<html>
<body>
<p>This is a paragraph <!-- and a comment --></p>
</body>
</html>

我想提取<p>标签的整个文本,包括<!-- and a comment -->. 使用 .get_text() 仅返回“这是一个段落”。

我想要这样的整个原始文本:This is a paragraph <!-- and a comment -->.

如何使用 beautifulsoup4 实现这一点?

标签: pythonbeautifulsoup

解决方案


找到p标签并使用text属性获取其文本:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)

for para_tag in soup.find_all('p'):
    print(para_tag.text)

编辑

如果您也在标签内寻找评论,您可以使用commentimport from bs4

s = """
<html>
<body>
<p>This is a paragraph <!-- and a comment --></p>
</body>
</html>
"""
from bs4 import BeautifulSoup
from bs4 import Comment
soup = BeautifulSoup(s)

for para_tag, comment in zip(soup.find_all('p'), soup.find_all(text=lambda text: isinstance(text, Comment))):
    if comment:
       print(para_tag.text, "<!--" + comment + "-->")
    else:
        print(para_tag.text)

编辑2:

使用.decode_contents()

for para_tag, comment in soup.find_all('p'):
       print(para_tag.decode_contents())

输出:

This is a paragraph <!-- and a comment -->

推荐阅读