获取所有子元素


Answers:


122

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

但是,这听起来并不像查找一个元素的所有子元素的有效用例。要获得所有直接/间接孩子都是昂贵的手术。请进一步说明您要做什么。应该有更好的方法。

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
只是弄清楚的是,.之前//是很重要的,如果点丢失,即使你从一个元素调用该方法,它再次搜索整个HTML
六合阿隆

61

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

HTML示例:

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

您可以这样使用find_elements_by_

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

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


* find_element_by_class_name
Iorek'7

1

的另一种崇拜find_elements_by_xpath(".//*")是:

from selenium.webdriver.common.by import By


find_elements(By.XPATH, ".//*")

-1

这是获取子元素的代码(在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++;
    }
 }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.