使用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
相关产品推荐
相关产品推荐

