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

如何用Python BeautifulSoup获取div元素的父节点属性

How to Get Parent Item's data Attribute for Target Divs

Hey there! I see you're trying to grab the data attribute values from the parent <item> nodes that contain those <div>s with "EXAMPLE" text. Let's fix this up step by step.

First, Let's Break Down the Issue

Your current code finds the matching <div>s, but it doesn't link them back to their parent <item> elements. That's why you're getting the div text output but not the parent attributes you need.

Solution 1: Target Divs First, Then Traverse Up to Parent Item

This approach first locates all the <div>s with text matching "EXAMPLE", then grabs their parent <item>'s data attribute:

import re
from bs4 import BeautifulSoup

# Replace 'code' with your actual HTML content
soup = BeautifulSoup(code, "html.parser")

# Find all divs with the correct class and text pattern
matching_divs = soup.find_all(
    "div",
    class_="exampleclass",
    text=re.compile(r"EXAMPLE")
)

# Loop through each div and extract its parent item's data attribute
for div in matching_divs:
    parent_item = div.parent
    # Verify the parent is an <item> with a data attribute before accessing
    if parent_item.name == "item" and parent_item.has_attr("data"):
        print(parent_item["data"])

Solution 2: Iterate Over Items and Check Their Child Divs

Alternatively, you can loop through each <item> first, then check if it contains a matching <div>—if it does, extract the item's data attribute:

import re
from bs4 import BeautifulSoup

soup = BeautifulSoup(code, "html.parser")

# Loop through every <item> with class "info"
for item in soup.find_all("item", class_="info"):
    # Look for the target div inside this specific item
    target_div = item.find(
        "div",
        class_="exampleclass",
        text=re.compile(r"EXAMPLE")
    )
    # If we found the div, grab the item's data attribute
    if target_div:
        print(item["data"])

What This Does

Both solutions will output exactly what you're looking for:

findthisinfo
findthisinfo1

The key here is linking the matching <div> directly to its parent <item>—either by traversing up from the div, or by checking each item's child divs first.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:32:58