【问题标题】:Problem uploading file with selenium webdriver + python使用 selenium webdriver + python 上传文件的问题
【发布时间】:2020-09-13 10:03:48
【问题描述】:

我在使用 selenium 和 python 上传文件时遇到问题。主要问题是选择文件路径的文本框被禁用,因此,当我将绝对路径放入 send_keys 时,什么都不做。

如何使用 JS 或其他方法处理对话框窗口(在我的工作中,我无法安装 PyAutoIt 或任何框架)

html代码是这样的:

<div class="form-inline actions-toolbar">
        <input disabled="disabled" class="input-xxxlarge" id="uploadFile" style="background: rgb(255, 255, 255); margin-left: 10px;" placeholder=""> --> This is the textBox
        <div class="fileUpload btn btn-primary">
            <span>Explorar</span>
        <input name="fileUpload" tabindex="1" class="upload" id="fileUpload" onchange="showPath(this);" type="file" size="50" accept=".txt"> --> This is the button "Search"
        </div>
        <input name="batchPaymentFilePath" id="batchPaymentFilePath" type="hidden" value="">
        <button disabled="disabled" class="btn" id="uploadButton" onclick="validNavigation = true;myFunction();"><i class="icon-upload-alt"></i> &nbsp;Cargar</button> --> Button to load File

    </div>

python代码是这样的:

    filePath = os.path.abspath('C:\\file\\path\\file_to_upload.txt')
driver.find_element_by_xpath('//*[@type="file"]').send_keys(filePath)

当我运行脚本时,上传文件对话框窗口只显示桌面,而不是绝对文件路径。

谢谢大家!

【问题讨论】:

  • 在您将文件路径发送到按钮的行之前,添加此行并尝试:driver.execute_script('document.querySelector("#uploadButton").removeAttribute("disabled");document.querySelector("#uploadButton").setAttribute("enabled", true);') 和一些time.sleep(2)

标签: python selenium-webdriver file-upload


【解决方案1】:

感谢@sowjanya-r-bhat,这是我对您与我分享的代码的更新:

    driver.execute_script('document.querySelector("#uploadFile").removeAttribute("disabled");document.querySelector("#uploadFile").setAttribute("enabled", true);')
#Enable the file text box
upload = driver.find_element_by_xpath('//*[@id="uploadFile"]')
#Send the file path
upload.send_keys("C:\\file\\path\\file_to_upload.txt")
#Enable Load Button
driver.execute_script('document.querySelector("#uploadButton").removeAttribute("disabled");document.querySelector("#uploadButton").setAttribute("enabled", true);')

我必须启用加载按钮,因为取决于在上传文件窗口中选择的文件。

再次感谢!

【讨论】:

    猜你喜欢
    • 2017-10-02
    • 2020-10-24
    • 2023-03-06
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2021-03-20
    • 2013-09-20
    相关资源
    最近更新 更多