获取所有子元素 [英] Get all child elements

查看:63
本文介绍了获取所有子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Python的Selenium中,可以将WebElement的所有子级作为列表获得吗?

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

推荐答案

是的,您可以通过find_elements_by_css_selector("*")find_elements_by_xpath(".//*")来实现.

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

这篇关于获取所有子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆