[Python] How to find direct children of element in lxml

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    I found an object with specific class:

    THREAD = TREE.find_class('thread')[0]


    Now I want to get all <p> elements that are its direct children.

    I tried:

    THREAD.findall("p")

    THREAD.xpath("//div[@class='thread']/p")


    But all of those returns all <p> elements inside this <div>, no matter if that <div> is their closest parent or not.

    How can I make it work?

    Edit:

    Sample html:

    <div class='thread'>
    <p> <!-- 1 -->
    <!-- Can be some others <p> objects inside, which should not be counted -->
    </p>
    <p><!-- 2 --></p>
    </div>
    <div class='thread'>
    <p>[...]</p>
    <p>[...]</p>
    </div>


    script should find two objects <p>, which are children of THREAD. I should receive list of two objects, marked as "1" and "2" in comments in sample HTML.

    Edit 2:

    Yet another clarification, since people get confused:

    THREAD is some object stored in variable, can be any html element. I want to find <p> objects that are direct children of THREAD. Those <p>'s can not be outside THREAD or inside any element that's also inside THREAD.

    Continue reading...

Compartilhe esta Página