BeautifulSoup:将顶级文本与经典标签查找功能相结合?
P粉471207302
P粉471207302 2023-09-15 09:16:45
[HTML讨论组]

我正在尝试使用 BeautifulSoup 从非统一结构的 html 块中提取信息。我正在寻找一种方法来组合搜索/过滤器输出中标签之间的文本块。例如,来自 html:

<span>
    <strong>Description</strong>
    Section1
    <ul>
        <li>line1</li>
        <li>line2</li>
        <li>line3</li>
    </ul>
    <strong>Section2</strong>
    Content2    
</span>

我想创建一个输出列表,忽略某些类型的标签(上例中的 ulli),但捕获顶级未标记文本。我发现的最接近的是 .select(':not(ul,li)').find_all(['strong']),但两者都不是它们可以同时捕获未标记的顶级文本和各种目标标记。理想的行为是这样的:

.find_all(['strong','UNTAGGED'])

产生如下输出:

[
<strong>Description</strong>,
Section1,
<strong>Section2</strong>,
Content2
]

P粉471207302
P粉471207302

全部回复(1)
P粉905144514

要获得输出,您可以先选择,然后选择它的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
输出
[<strong>Description</strong>,
 'Section1',
 <strong>Section2</strong>,
 'Content2']
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号