In Selenium with Python is it possible to get all the children of a WebElement as a list?
For the div element with an id attribute of hero //div[@id='hero'] , these XPath expression will select elements as follows: //div[@id='hero']/* will select all of its children elements. //div[@id='hero']/img will select all of its children img elements. //div[@id='hero']//* will select all of its descendent elements.
A child is an element that is directly below and connected to an element in the document tree.
The getElementsByTagName() method returns a collection of child elements with a given tag name. The getElementsByTagName() method returns a NodeList object.
Yes, you can achieve it by find_elements_by_css_selector("*")
or find_elements_by_xpath(".//*")
.
However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.
from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.stackoverflow.com") header = driver.find_element_by_id("header") # start from your target element, here for example, "header" all_children_by_css = header.find_elements_by_css_selector("*") all_children_by_xpath = header.find_elements_by_xpath(".//*") print 'len(all_children_by_css): ' + str(len(all_children_by_css)) print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With