Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all child elements

In Selenium with Python is it possible to get all the children of a WebElement as a list?

like image 688
walshie4 Avatar asked Jul 17 '14 05:07

walshie4


People also ask

How do I select all child elements in XPath?

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.

What are child elements in HTML?

A child is an element that is directly below and connected to an element in the document tree.

How do I get child element by tag?

The getElementsByTagName() method returns a collection of child elements with a given tag name. The getElementsByTagName() method returns a NodeList object.


1 Answers

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)) 
like image 122
Yi Zeng Avatar answered Sep 29 '22 14:09

Yi Zeng