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

如何在BeautifulSoup中使用select或find方法访问目标元素的父节点

实现方法

方法1:使用CSS :has()伪类(推荐)

BeautifulSoup 4.7.0及以上版本支持CSS的:has()伪类,可以直接匹配包含指定子元素的父节点,一步得到你需要的tr节点:

import requests
from bs4 import BeautifulSoup

response = requests.get("https://vip.mk.co.kr/newSt/rate/item_all.php?koskok=KOSPI&orderBy=upjong")
response.raise_for_status()
response.encoding= 'EUC-KR'
html = response.text
bs = BeautifulSoup(html, 'html.parser')

# 直接选择所有包含.st2类子元素的tr节点
result_trs = bs.select('tr:has(.st2)')

# 遍历提取数据示例
for tr in result_trs:
    td_list = tr.find_all('td')
    # 按顺序提取td内容
    stock_code = td_list[0].a['title']
    stock_name = td_list[0].text.strip()
    price = td_list[1].text.strip()
    change_range = td_list[2].text.strip()
    print(stock_code, stock_name, price, change_range)

方法2:遍历子元素获取父节点(全版本兼容)

如果你的BeautifulSoup版本较低不支持:has(),可以先选中所有.st2类的元素,再调用find_parent()方法获取对应的tr父节点:

import requests
from bs4 import BeautifulSoup

response = requests.get("https://vip.mk.co.kr/newSt/rate/item_all.php?koskok=KOSPI&orderBy=upjong")
response.raise_for_status()
response.encoding= 'EUC-KR'
html = response.text
bs = BeautifulSoup(html, 'html.parser')

result_trs = []
# 先获取所有.st2类的节点
st2_items = bs.select('.st2')
for item in st2_items:
    # 找到当前节点最近的tr父级,避免嵌套结构导致取到错误父节点
    tr_node = item.find_parent('tr')
    if tr_node:
        result_trs.append(tr_node)

# 后续提取数据的逻辑和方法1一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:15:07