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

如何使用Beautiful Soup查找指定父标签对应的子标签

问题诊断

你提供的代码存在两个核心问题:

  1. 语法错误:soup.find("span" class_= "DetailsSummary--extendedData--365A_")中标签参数"span"和class_参数之间缺少逗号,直接运行会触发语法报错。
  2. 定位逻辑错误:你选中的span.DetailsSummary--extendedData--365A_是预报卡片内的摘要文本标签,内部不存在你需要的details.Disclosure.themeList--25Q0H类元素,无法拿到返回结果。

解决方法

BeautifulSoup支持从指定父元素范围内查找后代元素,完全可以解决页面多元素类名重复的定位问题,有两种常用实现方式:

  • 先定位目标父元素,再调用父元素的find()/find_all()方法,匹配范围仅局限于父元素内部
  • 使用select()方法配合CSS层级选择器,直接链式匹配指定父层级下的子元素

修正后可运行代码

import requests
from bs4 import BeautifulSoup

page = requests.get("https://weather.com/en-IE/weather/tenday/l/e98742cdb581b2f4461e4f438badbfb0e16dc9e70ffbf4c8df1b0f7a4394f9f9")
soup = BeautifulSoup(page.content,"lxml")

# 方式1:父元素查找法
# 先定位到包含所有十天预报的父容器节点
parent_node = soup.find("div", class_="DailyForecast--DisclosureList--msYIJ")
# 仅在父容器内部查找符合条件的details元素
target_list = parent_node.find_all("details", class_ = "Disclosure themeList--25Q0H")
print(len(target_list)) # 输出为10,对应10天的预报项,定位正确

# 方式2:CSS选择器法
target_list2 = soup.select("div.DailyForecast--DisclosureList--msYIJ details.Disclosure.themeList--25Q0H")
print(len(target_list2)) # 同样输出10

通用规则

只要你能准确定位到唯一的上层父元素,在父元素上调用所有查找类方法时,都不会匹配到页面其他位置的同类名元素,可解决绝大多数同类定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:57:03