单击标记时发生StaleElementReferenceException



我每天都使用这个selenium代码下载一个文件,但有时会出现过时的引用错误。

如何确保在元素可用时立即单击它?

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êncian{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()

我建议使用带有try-except块的while循环,如下所示:

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êncian{ex.message}') 
except TimeoutException as ex:
print(f'Link de transferência não encontrado.n{ex}')
driver.quit()
succeed = True

我不知道你为什么要except TimeoutException as ex:。可能你可以删除它,只使用以下代码:

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 againn{ex.message}') 
driver.quit()

但我不确定。

相关内容

  • 没有找到相关文章

最新更新