python - 如何使用python从父标签中获取数据
问题描述
我需要使用 Python 从父标签中提取数据,而不考虑子标签。从下面的代码中,我需要得到“嗨,这是父标签”,而不是得到“嗨,这是子标签”。我怎样才能做到这一点?
<html>
<div>
"Hi, this is parent tag"
<span> "Hi, this is child tag" </span>
</div>
</html>
解决方案
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)))
输出:
“嗨,这是父标签”
推荐阅读
- c - 如果 scanf 无法获得正确的文字字符,它会返回什么?
- java - 我需要用 JDK 13.0.2 编译什么版本的 JRE?
- python - 当切换 /usr/bin/python 指向 python 3 时,除了 YUM 之外,还有什么会在 CentOS 7 中中断?
- node.js - 无法从 docker 实例连接到 neo4j
- python - pyparsing 通用 python 函数 args 和 kwargs
- swift - 快速创建 URLSession 冻结应用程序
- javascript - 如何在 Outloo 发送插件中区分会议取消和会议创建
- swift - 更新结构数组中的结构数组
- javascript - AG-Grid React,无法在数据更改时更新自定义单元格渲染器。函数组件的行为与类组件不同
- python - 尝试登录数据库时出现 sqlalchemy.exc.OperationalError