1

I'm using this selenium code to download a file daily, but sometimes I get stale reference error.

How can I be sure to click element as soon as it is avaiable?

try:
    btnMenu = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, 'TRANSFERÊNCIA')))
    # btnMenu = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.NAME, 'link2')))
    # WebDriverWait(driver, 10).until(EC.element_to_be_clickable(By.NAME, 'link2'))
    driver.execute_script("arguments[0].click();", btnMenu)
except StaleElementReferenceException as ex:
    print('Elemento obsoleto - botão transferência\n{ex.message}') 
    btnMenu = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.LINK_TEXT, 'TRANSFERÊNCIA')))
    driver.execute_script("arguments[0].click();", btnMenu)
except TimeoutException as ex:
    print(f'Link de transferência não encontrado.\n{ex}')
    driver.quit()
Prophet
  • 32,350
  • 22
  • 54
  • 79
nanquim
  • 1,786
  • 7
  • 32
  • 50

1 Answers1

1

I would suggest using a while loop with a try-except block as following:

succeed = False
while !succeed:
    try:
        btnMenu = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, 'TRANSFERÊNCIA')))
        driver.execute_script("arguments[0].click();", btnMenu)
        succeed = True
    except StaleElementReferenceException as ex:
        print('Elemento obsoleto - botão transferência\n{ex.message}') 
    except TimeoutException as ex:
        print(f'Link de transferência não encontrado.\n{ex}')
        driver.quit()
        succeed = True

I'm not sure why you having the except TimeoutException as ex:. Possibly you can remove it and use the following code only:

succeed = False
while !succeed:
    try:
        btnMenu = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, 'TRANSFERÊNCIA')))
        driver.execute_script("arguments[0].click();", btnMenu)
        succeed = True
    except:
        print('Failed clicking the button, going to try again\n{ex.message}') 
driver.quit()

But I'm not sure about that.

Prophet
  • 32,350
  • 22
  • 54
  • 79