Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first layer sub elements only in python selenium

How can I get a list of only the first layer child elements in selenium python?

I want something similar to what is described here: Selenium Python get all children elements

However, I only want the first layer sub elements. I have attached a picture to explain.

sub list problem

if I do as is described in the other entry I get all sub and sub sub....... elements. I just want the first layer like the 4 div elements shown in the image not the 8 sub sub elements.

like image 891
user2808967 Avatar asked Jun 14 '26 20:06

user2808967


2 Answers

Updated as of version 4.8.3

It's:

from selenium.webdriver.common.by import By

elem.find_elements(By.XPATH, "./*")

When you put ".//*", it gets all possible children in the tree, but with one slash "./*" only gets the children of the next level.

like image 154
Mijail Avatar answered Jun 17 '26 08:06

Mijail


Yes, you need to specify a direct parent-child relationship which can be done in XPath via a single / and in CSS selectors via >:

driver.find_elements_by_xpath("//section[@id = 'irq']/div/div[@eid]")
driver.find_elements_by_css_selector("section#irq > div > div[eid]")

Please recheck the irq and eid if I got them right from the screenshot (it is a bit blurry).

like image 37
alecxe Avatar answered Jun 17 '26 09:06

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!