Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium - get all children divs but not grandchildren

I'm trying to parse a html file. There are many nested divs in this html. I want to get all child divs, but not grandchildren etc.

Here is a pattern:

<div class='main_div'>
    <div class='child_1'>
        <div class='grandchild_1'></div>
    </div>
    <div class='child_2'>
        ...
        ...
</div>

So the command I'm looking for would return 2 elements - divs which classes are 'child_1' and 'child_2'.

Is it possible?

I've tried to use main_div.find_elements_by_tag_name('div') but it returned all nested divs in the div.

like image 710
Milano Avatar asked Jun 21 '15 12:06

Milano


People also ask

How do you get children of elements in selenium?

We can locate child nodes of web elements with Selenium webdriver. First of all we need to identify the parent element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the children with the findElements(By. xpath()) method.

Can we get xpath from Webelement?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

Where is parent element in selenium?

First of all we have to identify the known element with the help of any of the locators like id, classname and so on. Then we have to identify its parent element with findElement(By. xpath()) method. Also we can identify the parent element of a known element with the help of Javascript Executor.


1 Answers

Here is a way to find the direct div children of the div with class name "main_div":

driver.find_elements_by_xpath('//div[@class="main_div"]/div')

The key here is the use of a single slash which would make the search inside the "main_div" non-recursive finding only direct div children.

Or, with a CSS selector:

driver.find_elements_by_css_selector("div.main_div > div")
like image 71
alecxe Avatar answered Sep 18 '22 07:09

alecxe