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

如何使用BeautifulSoup选择包含指定id span的div元素

提取包含指定属性span的div文本方案

需求说明

仅提取满足以下两个条件的div中的文本:

  • div的class属性为class1
  • div内部包含id属性为span1的span元素

示例HTML结构

<div class="class1" > 
  <span id="span1"></span>
  text to scrape
</div>
<div class="class1" > 
  <span id="span2"></span>
  text to scrape
</div>
<div class="class1" > 
  <span id="span1"></span>
  text to scrape
</div>
<div class="class1" > 
  <span id="span3"></span>
  text to scrape
</div>

代码实现

原有代码修正

你原代码中查找span时误用了class_='span1'匹配class属性,实际要匹配id属性需改为id='span1',同时增加非空判断避免匹配不到span时报空指针错误:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
for div in soup.find_all(class_='class1'):
    target_span = div.find('span', id='span1')
    if target_span:
        print(div.text.strip())

更简洁的CSS选择器写法

可以直接用:has选择器一步定位符合条件的div,代码更简洁高效:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
for div in soup.select('div.class1:has(span#span1)'):
    print(div.text.strip())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:04