问题
I have a webpage which has multiple links and sub-links in flow as below
To click on the child elements (2,7,8 and so on...) I'm using driver.find_elements_by_xpath
(all of the sub-links can be found by combination of class & div) and looping if i have more than one link (technically a nested for loop for each child). Can this be optimized into a function, like a recursive Depth first search? Below is the code snippet which i tried.
def iterate_child_links():
elements = driver.find_elements_by_xpath(childpath)
element_count = len(elements)
single_element = driver.find_element_by_xpath(childpath)
if element_count == 1:
single_element = driver.find_element_by_xpath(childpath)
single_element.click() # JUST TO CLICK AND PROCEED TO THE NEXT
elif element_count > 1: # LOOP FOR EACH CHILD
splitnode_paths.append(driver.current_url)
elements = driver.find_elements_by_xpath(childpath)
for j in elements:
x = driver.find_element_by_xpath(childpath)
text = x.get_attribute('innerHTML')
print(text)
splitnode_paths.append(text)
for k in range(element_count):
html_text = elements[k].get_attribute('innerHTML')
if (html_text in splitnode_paths):
elements[k + 1].click()
else:
elements[k].click()
来源:https://stackoverflow.com/questions/64884227/traverse-links-and-sub-links-by-clicking-on-elements-selenium-python