首页 > 解决方案 > 如何使用python从父标签中获取数据

问题描述

我需要使用 Python 从父标签中提取数据,而不考虑子标签。从下面的代码中,我需要得到“嗨,这是父标签”,而不是得到“嗨,这是子标签”。我怎样才能做到这一点?

<html>
    <div>
        "Hi, this is parent tag"
        <span> "Hi, this is child tag" </span>
    </div>
</html>

标签: pythonhtmlbeautifulsoup

解决方案


from bs4 import BeautifulSoup

txt = """
<html>
    <div>
        "Hi, this is parent tag"
        <span> "Hi, this is child tag" </span>
    </div>
</html>
"""

soup = BeautifulSoup(txt)

for node in soup.findAll('div'):
    print(' '.join(node.findAll(text=True, recursive=False)))

输出:

“嗨,这是父标签”


推荐阅读