I have html structure:
<div class="parent" data-index="0"><div class="sub">...</div></div>
<div class="parent" data-index="1"><div class="sub">...</div></div>
When I click on some parent element and all sub elements changes classes like so:
<div class="parent selected" data-index="0"><div class="sub selected">...</div></div>
<div class="parent" data-index="1"><div class="sub">...</div></div>
I want to loop over all parents and their sub elements with selenium no matter whether element is clicked or not Right now I am doing this like so:
for i in range(n):
parent= driver.find_element_by_xpath(f"//div[@class='parent' and @data-index='{i}']")
for elem in parent.find_elements_by_xpath("./div"):
do_something(elem)
However this doesn't catch parent elements which are clicked.
I also tried to change the xpath to "//div[starts-with(@class,'parent') and @data-index='{i}']"
which catch also clicked parent elements.
But then parent.find_elements_by_xpath("./div")
returns empty list
I am not sure what I am doing wrong. I am looking forward for any suggestions. Thanks in advance.
CodePudding user response:
You can try this way
parent.find_element_by_xpath(".//div")
CodePudding user response:
You can try find_by_class_name
like:
for parent in driver.find_elements_by_class_name("parent"):
for sub in parent.find_elements_by_class_name("sub"):
do_something(sub)
Since both class="parent selected"
and class="parent"
are assigned to class parent
that single query would select all parents (including selected ones)
CodePudding user response:
Try like this once:
parents = driver.find_element_by_xpath("//div[contains(@class,'parent')]") # this xpath should highlight all the "div" tags which has "parent" in its class.
for parent in parents:
elements = parent.find_elements_by_xpath("./div") # this should give all the child "div" tags. If they are nested use ".//div"