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

如何用BeautifulSoup获取包含指定字符串的标签的全部文本内容

优化方案

你可以直接在遍历li元素时同步做条件判断和文本提取,一步拿到结果:

import re
facts_with_is2 = [
    li.get_text() 
    for li in webpage.select('ul.fun-facts li') 
    if li.find(string=re.compile('is'))
]

不需要先存储匹配到的部分文本再回溯找父节点,逻辑更直接。如果不需要正则的模糊匹配,还可以简化写法,执行效率更高:

facts_with_is2 = [
    li.get_text() 
    for li in webpage.select('ul.fun-facts li') 
    if 'is' in li.get_text()
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:36:03