我每天都使用这个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()
但我不确定。