You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup提取HTML标签直接文本时的异常问题排查

问题原因及解决办法

问题根源

tag.find(string=True, recursive=False) 只会返回第一个匹配的文本节点。在你的案例里,<div> 下的第一个内容是 <i> 标签前的空白字符(属于文本节点),所以find()直接返回了这个空白文本,跳过了后面的FF Services文本节点。

解决方法

如果要获取标签下所有直接子文本节点并整理,改用 tag.find_all(string=True, recursive=False),过滤空白文本后拼接即可:

from bs4 import BeautifulSoup
soup = BeautifulSoup('<div> <i> </i> FF Services </div>', "html.parser")
for tag in soup.find_all():
    direct_texts = tag.find_all(string=True, recursive=False)
    # 过滤空白内容并拼接有效文本
    clean_text = ''.join([text.strip() for text in direct_texts if text.strip()])
    print(tag, ':', clean_text)

输出结果:

<div> <i> </i> FF Services </div> : FF Services
<i> </i> : 

也可以通过遍历tag.contents筛选文本节点处理:

for tag in soup.find_all():
    clean_text = ''.join([node.strip() for node in tag.contents if isinstance(node, str) and node.strip()])
    print(tag, ':', clean_text)

内容的提问来源于stack exchange,提问作者Minions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:02:00