保存使用Python Selenium上传的文件

我正在使用Python在Selenium中工作,并且正在使用Chrome。当我到达上传图片的部分时,我将执行以下操作:

    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”。我能够与图片进行交互以缩小图像,等等。但是,当我单击“保存”(手动或使用程序)时,新图片不会保存。叠加层消失了,旧照片仍在显示。如果我手动选择要上传的文件,然后单击“保存”,则可以正常工作。只是当我使用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>
yantingshuang 回答:保存使用Python Selenium上传的文件

如果文件仍通过您的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”标签的元素,该元素与您要单击的按钮相对应

本文链接:https://www.f2er.com/3123388.html

大家都在问