【问题标题】:Unable to upload file by sendkeys into button element within iframe using selenium with python无法使用 selenium 和 python 通过 sendkeys 将文件上传到 iframe 中的按钮元素
【发布时间】:2015-03-28 04:31:08
【问题描述】:

[环境]:Python + Selenium

我正在尝试将本地文件上传到上传文件按钮。

首先,我尝试查看是否可以找到该元素并单击该按钮,然后使用成功

driver.switch_to_frame("upload_frame")
driver.find_elements(By.ID, 'id_file').click()

所以,我使用相同的方式,但将click() 替换为send_keys() 用于文件上传。

driver.switch_to_frame("upload_frame")
driver.find_elements(By.ID, 'id_file').send_keys("xxx.bin")

但它不能将值传入。

所以,我尝试使用以下其他定位器:(它们都不能工作)

driver.find_element(By.XPATH, "//button[text()='Update from File']")
driver.find_elements(By.XPATH, "//*[@id='id_file']")
driver.find_elements(By.XPATH, "//input[@id='file']")

此外,我还用谷歌搜索了很多类似的问题,但找不到解决方案/答案。

想征求您的意见并让我对此有所了解吗? 谢谢。

HTML代码n-p:

<iframe id="upload_frame" height="30px" frameborder="0" width="0" src="/web/setting/upload.html?r=1422498136526" scrolling="no"
name="upload_frame" style="width: 170px;">
    <!DOCTYPE html>
    <html>

    <head>

        <body onload="page_load();">
            <div id="content" class="b1">
                <form id="form_firm" action="/cgi-bin/system_mgr.cgi" enctype="multipart/form-data" method="post" name="form_firm">
                    <input type="hidden" value="cgi_firmware_upload" name="cmd">
                    <div class="file_input_div">
                        <button id="id_file" type="button" style="border: 2px solid rgb(70, 70, 70); background: none repeat scroll 0% 0% rgb(33, 33, 33);">
                            <span class="_text" lang="_firmware" datafld="update_b">Update from File</span>
                        </button>
                        <input id="file" class="file_input_hidden" type="file" onchange="start_upload();" onclick="clear_upload_path();" style="cursor:pointer"
                        name="file">
                    </div>
                </form>
            </div>
        </body>

    </html>
</iframe>

【问题讨论】:

    标签: python html selenium selenium-webdriver


    【解决方案1】:

    driver.find_elements(By.ID, 'id_file').send_keys("xxx.bin") 不起作用,因为它对应于 button element 而不是带有文件类型的 input element

    对于使用 selenium 的简单文件上传,您必须首先搜索类型为文件的输入标签。就像在您的代码中一样,那必须是

    &lt;input id="file" class="file_input_hidden" type="file" onchange="start_upload();" onclick="clear_upload_path();" style="cursor:pointer" name="file"&gt;

    请使用以下代码进行文件上传:

    driver.switch_to_frame("upload_frame")
    driver.find_element(By.ID, 'file').send_keys('//path of the file to upload')
    

    注意:-上面对应的是“文件类型的输入标签”

    【讨论】:

    • 感谢您指出 send_keys() 需要与输入标签一起使用。现在,它通过使用“文件”ID 来工作。欣赏!
    • 嗨,Subh 如果输入类型不是“文件”而是“按钮”,你知道如何发送文件吗?我使用相同的方式将文件名发送到由 ID 定位的元素中,但它似乎不起作用。
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    相关资源
    最近更新 更多