保存使用Python上传的文件时出错

2024-10-03 02:46:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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)

这似乎如预期的那样工作,在保存新图片之前,图片会弹出一个用于剪切/缩放的覆盖图。覆盖图是一个div class=“modal box” id="croppicModal."  I am able to interact with the picture to zoom out and whatnot.  But when I click "Save" (either manually or using my program), the new picture does not save.  The overlay just goes away and the old picture is still showing.  If I manually choose the file to upload and then click "Save," it works fine.  It's just when I use the send_keys command to upload the photo that I then can't actually save it.  Any ideas why? Here is the Save button:

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

Tags: andthetodivmysave图片class
3条回答

如果文件仍然通过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) 

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

您正在尝试单击不是按钮的div元素。您需要找到带有“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的约定是对变量使用小写

相关问题 更多 >