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

如何使用BeautifulSoup选择无标识的第4个子div并获取文本

解决方法

你的代码存在两个关键问题:

  1. 查找主div时id参数写错:HTML里主div的id是main_div,但你写的是main,导致无法定位到目标父元素。
  2. 缺少获取第4个子div的逻辑。

下面是几种可行的实现方式:

方法一:通过find_all获取子元素后按索引取值

from bs4 import BeautifulSoup

# 假设r.text是你的HTML内容
soup = BeautifulSoup(r.text, 'html.parser')
# 正确定位主div
main_div = soup.find('div', id='main_div')
# 索引从0开始,第4个子div对应索引3
fourth_div_text = main_div.find_all('div')[3].text.strip()
print(fourth_div_text)  # 输出:div text 04

方法二:使用CSS选择器直接定位

利用CSS选择器:nth-of-type(4)可以直接选中父元素下的第4个div:

from bs4 import BeautifulSoup

soup = BeautifulSoup(r.text, 'html.parser')
# 用CSS选择器定位目标元素
fourth_div = soup.select_one('#main_div > div:nth-of-type(4)')
fourth_div_text = fourth_div.text.strip()
print(fourth_div_text)  # 输出:div text 04

方法三:遍历children过滤获取

from bs4 import BeautifulSoup

soup = BeautifulSoup(r.text, 'html.parser')
main_div = soup.find('div', id='main_div')
# 过滤空白节点,只保留div子元素
div_children = [child for child in main_div.children if child.name == 'div']
fourth_div_text = div_children[3].text.strip()
print(fourth_div_text)  # 输出:div text 04

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:01:10