首页 > 解决方案 > 等到 send_keys 完成单击按钮(使用 Selenium)

问题描述

我正在学习 Selenium 并尝试自动执行一项任务。该任务包括从典型输入文件上传一个 zip 文件并单击上传按钮。我已经让它工作了,但有时它会失败,因为在 send_keys 完成之前按下了上传按钮,并且页面显示一个对话框,说没有要上传的内容。

这是代码:

driver = webdriver.Firefox()
driver.get('http://localhost:8008/management/#/welcome')
WebDriverWait(driver, 15).until(
EC.url_matches('http://localhost:8008/management/#/welcome'))
driver.get('http://localhost:8008/management/#/configuration-engines')
WebDriverWait(driver, 15).until(EC.url_matches('http://localhost:8008/management/#/configuration-engines'))
WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.ID, 'userfile'))).send_keys(file_path)
WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.ID, 'upload_and_install')))
button = driver.find_element_by_id('upload_and_install').click()

这是输入的 HTML 代码(无论有没有文件,它都不会改变。它们没有值来检查它是否已经改变):

<input type="file" name="file[]" id="userfile" dir="ltr">

我找到的解决方案是简单地做一个 time.sleep(5),但我想知道是否有更“干净”的方式。

标签: pythonselenium

解决方案


正如OP所提到的,有一个轮子旋转,我建议你使用ExplicitWait - invisibility_of_element

示例代码:

WebDriverWait(driver, 20).until(EC.invisibility_of_element((By.XPATH, "Wheel spining xpath"))) 

此行将等待提供的 xpath 不可见。


推荐阅读