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

如何用Beautiful Soup提取金额并剔除嵌套的project-votes span元素?

解决Beautiful Soup提取金额文本的问题

方法1:直接提取外层span的子文本节点

金额是外层span的直接文本内容,嵌套的<span class="project-votes">是独立子元素,我们可以通过筛选文本节点来提取金额:

for target_span in soup.find_all("span", {"class": "budget-list__data__number budget-list__number show-for-medium"}):
    # 筛选外层span的直接文本节点,去除空白后拼接
    amount_text = ' '.join([text.strip() for text in target_span.contents if isinstance(text, str) and text.strip()])
    print(amount_text)  # 输出示例:4 000 €

方法2:移除嵌套span后提取文本

先定位并移除嵌套的投票span元素,再获取清理后的文本:

for target_span in soup.find_all("span", {"class": "budget-list__data__number budget-list__number show-for-medium"}):
    # 找到嵌套的project-votes元素
    vote_span = target_span.find("span", class_="project-votes")
    if vote_span:
        vote_span.decompose()  # 从文档树中彻底移除该元素
    # 获取去除多余空白的文本
    amount_text = target_span.get_text(strip=True)
    print(amount_text)

为什么span.clear()无效?

clear()方法会删除当前元素的所有子节点和文本内容,执行后外层span会变成空标签,自然无法获取金额。你需要的是移除特定的嵌套元素,而非清空全部内容。

内容的提问来源于stack exchange,提问作者Weierstraß Ramirez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:15:42