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.
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With