Selenium Python get all children elements

匿名 (未验证) 提交于 2019-12-03 01:17:01

问题:

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

回答1:

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)) 


回答2:

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

  • one
  • two
  • three

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class("bar") elementList = parentElement.find_elements_by_tag_name("li") 

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!