How to find direct children of element in lxml

后端 未结 3 1284
走了就别回头了
走了就别回头了 2021-01-14 09:00

I found an object with specific class:

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

Now I want to get all

elements that a

3条回答
  •  梦毁少年i
    2021-01-14 09:46

    Try this XPath expression:

    //p[parent::div[@class='thread']]
    

    Or in a complete Python expression:

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

    The other (inverse) approach is this XPath expression:

    div[@class='thread']/child::p"
    

    which uses the direct child:: axis and only selects the direct child nodes.

    Summary:
    Which one of both expressions is faster depends on the XPath compiler. child:: is the default axis and is used if no other axis is given.


    FYI: XPath counting starts at 1 and not 0.
    So concerning your XML example, the following expression

    count(//div[@class='thread'][1]/child::p)
    

    does result in a value of 2 - the result of counting

    +

    .

提交回复
热议问题