Python 获取所有子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24795198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:12:38  来源:igfitidea点击:

Get all child elements

pythonseleniumselenium-webdriver

提问by walshie4

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

在使用 Python 的 Selenium 中,是否可以将 WebElement 的所有子项作为列表?

采纳答案by Yi Zeng

Yes, you can achieve it by find_elements_by_css_selector("*")or find_elements_by_xpath(".//*").

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

However, this doesn't sound like a valid use case to find all childrenof 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))

回答by Richard

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

是的,您可以使用find_elements_by_将子元素检索到列表中。在此处查看 python 绑定:http: //selenium-python.readthedocs.io/locating-elements.html

Example HTML:

示例 HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_like so:

你可以这样使用find_elements_by_

parentElement = driver.find_element_by_class_name("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.

如果您需要特定案例的帮助,可以使用要从中获取父元素和子元素的 HTML 来编辑帖子。

回答by shikha nagar

Here is a code to get the child elements (In java):

这是获取子元素的代码(在java中):

String childTag = childElement.getTagName();
if(childTag.equals("html")) 
{
    return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath("..")); 
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++) 
{
    WebElement childrenElement = childrenElements.get(i);
    String childrenElementTag = childrenElement.getTagName();
    if(childTag.equals(childrenElementTag)) 
    {
        count++;
    }
 }