简体   繁体   中英

How can I select the next one-level element?

How can i select next element after another (all elements placed in one-level).

For example i have this code:

from lxml import etree

html = """
    <div class="latest">
        <div class="root">  root1   </div>
        <div class="root">  root2   </div>
        <div class="root">  root3   </div>
        <div class="child"> child1  </div>
        <div class="child"> child2  </div>
        <div class="child"> child3  </div>
        <div class="root">  root4   </div>
    </div>
"""

tree = etree.HTML(html)

for i in tree.xpath('//div[@class="root"]'):
    # how i can do it? 
    next = i.etree('next div[@class="child"]')
    if next:
        # there i want doing something with `next`
        print 1
    else:
        print 0

You appear to need an XPath axis operation . It's not fully clear what your desired output is, but I'll explain the tools you need to get there.

for div in doc.xpath('//div[@class="root"]'):
     children = div.xpath('following-sibling::div[@class="child"]')
     if children:
         print('yes')
     else:
         print('no')

yes
yes
yes
no

This axis operation says: give me a list of all of the siblings after the current node which are named div and have attribute class="child" . In this case obviously the first 3 root nodes have the same list of 3 children, and the last has a list of 0.

If instead you only wanted to look at the very next sibling and check if it is class="child" you can do that too:

for div in doc.xpath('//div[@class="root"]'):
     first_sib = div.xpath('following-sibling::*[1]')
     # `first_sib` is either a 0- or 1-length list, handle both gracefully
     if first_sib and first_sib[0].get('class') == 'child':
         print('yup')
     else:
         print('nope')

nope
nope
yup
nope

The MDN link above has more axes operations and some pretty good tutorials (though they can get a bit javascript-oriented in places).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM