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

如何将map()对象转为Beautiful Soup可迭代对象?并使用map()简化HTML元素提取的嵌套循环代码

问题:能否用map()简化Beautiful Soup的嵌套遍历代码?

我正在用Beautiful Soup库遍历已下载的HTML代码,目标是提取特定元素的文本,不过这些元素需要通过嵌套循环才能确保获取正确内容,目前我的代码是这样的:

elist = []
if package.find('div', class_='kernel'):
    for g in package.find_all('div', class_='kernel'):
        for h in g.find_all('pre', class_='screen'):
            elist.extend(h.find('code', class_='literal'))

我想知道能不能用map()函数把这段代码简化(甚至写成一行)?我自己尝试过下面的写法:

elist1 = list(map(lambda x: x if package.find('div', class_='kernel') else None, package.find_all('div', class_='kernel')))

但这样之后还是得遍历返回的elist1,再调用Beautiful Soup的find_all方法才能拿到正确元素。想问下有没有办法让map()对象直接返回Beautiful Soup的可迭代类?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:19:03