Traverse links and sub-links by clicking on elements selenium python

☆樱花仙子☆ 提交于 2021-02-08 09:56:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!