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

如何用BeautifulSoup获取div下的所有子span元素?

问题解决步骤

核心错误分析

  1. soup.find_all()返回的是BeautifulSoup结果集(类似列表),不能直接调用.find_all()方法,必须遍历每个元素单独处理。
  2. 代码中定位的div类与目标div不符,需要先定位到包含两个<span>的目标容器,再提取子元素。

修正后的代码

情况1:目标div是col-12...类div的子元素

from bs4 import BeautifulSoup

# 假设你已获取页面HTML内容到soup对象中
items = soup.find_all("div", {"class": "col-12 col-sm-6 product--description--content--item"})

total_spans = 0
for item in items:
    # 定位到包含两个span的目标div
    target_div = item.find("div", {"class": "d-flex justify-content-between font-size-14 font-weight-bold"})
    if target_div:
        # 获取该div下所有span元素
        spans = target_div.find_all("span")
        total_spans += len(spans)
        # 打印每个span的文本(自动去除前后空白)
        for span in spans:
            print(span.get_text(strip=True))

print(f"总共找到{total_spans}个span元素")

情况2:直接定位目标div

如果无需通过父容器,可直接定位带d-flex...类的div:

from bs4 import BeautifulSoup

# 直接定位目标div集合
target_divs = soup.find_all("div", {"class": "d-flex justify-content-between font-size-14 font-weight-bold"})

total_spans = 0
for div in target_divs:
    spans = div.find_all("span")
    total_spans += len(spans)
    for span in spans:
        print(span.get_text(strip=True))

print(f"总共找到{total_spans}个span元素")

关键说明

  • get_text(strip=True)可以自动去除span文本前后的缩进、换行等空白字符,让结果更整洁。
  • 务必确认HTML结构的层级关系,避免定位错误的容器导致无法获取目标元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:22:37