无法保存使用 Python Selenium 上传的文件

Trouble saving file uploaded using Python Selenium

我正在使用 Python 和 Chrome 在 Selenium 中工作。当我进入图片上传部分时,我执行以下操作:

    pictureChange = driver.find_element_by_xpath("//input[@class='custom-file' and @type='file']")
    photoLocation = [I enter the file location on my locally mapped drive]
    pictureChange.send_keys(photoLocation)

这似乎按预期工作,并且在保存新图片之前图片会在 cropping/zooming 的叠加层中弹出。叠加层是 div class="modal-box" id="croppicModal." 我可以与图片互动以缩小等等。但是当我单击 "Save"(手动或使用我的程序)时,新图片不会保存。叠加层消失了,旧图片仍在显示。如果我手动选择要上传的文件,然后单击 "Save,",它就可以正常工作。只是当我使用 send_keys 命令上传照片时,我实际上无法保存它。任何想法为什么?这是保存按钮:

    <div class="action-btns"><span class="save-btn rounded-btn">Save</span><span class="croppic-cancel white-btn cancel-btn">Cancel</span></div>

如果文件仍在通过您的 send_keys 策略上传,我认为问题不在于上传,而在于用于保存文件的方法。我不确定你使用的是什么点击策略,但你可以尝试用一些 Javascript.

来改变它
# locate save button
save_button = driver.find_element_by_xpath("//span[text()='Save']")

# click save button with JS
driver.execute_script("arguments[0].click();", save_button) 

如果这不起作用,我们可以更改您上传文件的方式,看看是否有帮助。但我不相信实际上传是这里的问题。

我会尝试使用 WebDriverWait:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 10)
picture_change = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@class='custom-file' and @type='file']")))
photo_location = "Path/to/the/file"
picture_change.click()
picture_change.send_keys(photo_location)

save_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Save']")))
save_button.click()

仅供参考:python 约定是对变量使用小写

您正试图点击 div 不是按钮的元素。您需要找到带有 "button" 标签且与您尝试点击的按钮相对应的元素