如何使用Selenium WebDriver python访问隐藏文件上载字段

时间:2015-06-15 11:41:45

标签: python selenium selenium-webdriver

我有这样的HTML:

<a id="buttonToUpload" class="btn-pink medium" href="#">
    <span class="icon-arrow-right">upload photo</span>
</a>
<form id="form1" enctype="multipart/form-data">
    <input id="uploadImage" type="file" accept="image/png, image/gif, image/jpeg, image/jpg" style="visibility: hidden">
</form>

按下“提升系统”对话框以选择文件,我无法通过webdriver访问该文件。 我直接尝试了send_keys(),但它引发了ElementNotVisibleException。那么如何在那里上传照片呢? 实际代码:

driver = webdriver.Firefox()
driver.get('http://www........')
upload_input = driver.find_element_by_id('uploadImage')
upload_input.send_keys(os.getcwd()+'/image.jpg')

3 个答案:

答案 0 :(得分:2)

解决了这个问题:

driver.execute_script("document.getElementById('uploadImage'‌​).style.visibility='‌​visible'")

答案 1 :(得分:1)

执行JavaScript以使输入元素在与之交互之前可见。

driver.execute_script("""document.querySelector("div.yourClassNameHere input[type=file]").style.display='block'""")

# Send the absolute file path of the file to the input element
input = browser.find_element(:xpath, "//input[@type='file']")
input.sendKeys(os.path.abspath("image.jpg"))

确保将查询替换为对您有意义的查询。

答案 2 :(得分:0)

我自己遇到了这个问题,在将硒与黄瓜一起使用时,我的“输入”元素看起来像这样:

<input type="file" autocomplete="off" tabindex="-1" style="display: none;">

这是我解决的方法:

JavascriptExecutor jse =(JavascriptExecutor) StepDef.driver;
        jse.executeScript("document.querySelector('" + elementSelector +"').style.display='block';");

        util.elementXpathIsVisible(elementXpath);
        StepDef.driver.findElement(By.xpath(elementXpath)).sendKeys(filePath);