我正在尝试使用 BeautifulSoup 从非统一结构的 html 块中提取信息。我正在寻找一种方法来组合搜索/过滤器输出中标签之间的文本块。例如,来自 html:
<span>
<strong>Description</strong>
Section1
<ul>
<li>line1</li>
<li>line2</li>
<li>line3</li>
</ul>
<strong>Section2</strong>
Content2
</span>
我想创建一个输出列表,忽略某些类型的标签(上例中的 ul 和 li),但捕获顶级未标记文本。我发现的最接近的是 .select(':not(ul,li)') 或 .find_all(['strong']),但两者都不是它们可以同时捕获未标记的顶级文本和各种目标标记。理想的行为是这样的:
.find_all(['strong','UNTAGGED'])
产生如下输出:
[ <strong>Description</strong>, Section1, <strong>Section2</strong>, Content2 ]
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要获得输出,您可以先选择
,然后选择它的next_sibling。示例
from bs4 import BeautifulSoup html = ''' <span> <strong>Description</strong> Section1 <ul> <li>line1</li> <li>line2</li> <li>line3</li> </ul> <strong>Section2</strong> Content2 </span> ''' soup = BeautifulSoup(html) data = [] for e in soup.select('strong'): data.extend([e,e.next_sibling.strip()]) data输出