Selenium python stops iteration after the first five elements while there are more elements in the list

163 views Asked by At

I am writing a code to download some files from a webpage. The code starts fine and there are 27 files to download, but after the first 5 downloads, I get a ElementClickInterceptedException error for the following elements. Can anyone tell me why the code stops downloading the rest of the files?

Here is the (part of the) code:

        actions = ActionChains(driver)

        xlbr2 = driver.find_elements_by_xpath("//*[@class='mf mf-xbrl']")
        print(len(xlbr2))
        for link in range(4, 27):
            time.sleep(2)
            print(link)
            try:
                xlbr2 = driver.find_elements_by_xpath("//*[@class='mf mf-xbrl']")
                xlbr2 = driver.find_elements_by_xpath("//*[@class='mf mf-xbrl']")[link]
                actions.move_to_element(xlbr2).perform()
                xlbr2.click()
                # xlbr2 = driver.find_elements_by_xpath("//*[@class='mf mf-xbrl']")[link].click()
                time.sleep(1)
                download = driver.find_element_by_xpath('/html/body/div[2]/div[8]/div/div/div/div[1]/div/div[2]/ul/div/div[4]/a/button/i')
                print('downloading file...')
                download.click()
                time.sleep(2)
                driver.back()
                # time.sleep(2)

            except Exception as err:
                print(f"{type(err).__name__} was raised: {err}")
2

There are 2 answers

18
Prophet On

You did not share a link to the page you are working on, so I can't know what is the actual problem there, however I can guess you have to scroll the page in order to reach those elements.
It so something like this will help:

actions = ActionChains(driver)
xlbr2 = driver.find_elements_by_xpath("//*[@class='mf mf-xbrl']")
print(len(xlbr2))
for link in range(len(xlbr2)):
    time.sleep(2)
    print(link)
    try:
        xlbr2 = driver.find_elements_by_xpath("//*[@class='mf mf-xbrl']")[link]  
        actions.move_to_element(xlbr2).perform()            
        xlbr2.click()
        time.sleep(1)
        download = driver.find_element_by_css_selector('button.saveButton')
        print('downloading file...')
        download.click()
        time.sleep(2)
        driver.back()
        time.sleep(2)
    except Exception as err:
        print(f"{type(err).__name__} was raised: {err}")

You will have to import this

from selenium.webdriver.common.action_chains import ActionChains

It is also possible that there is some accept cookie banner on the bottom of the page that you should close...
need to see the actual page to give more precise answer.

0
Bakaveli On

driver.execute_script('arguments[0].click()', element) This solved the issue