由于输入类型=文件在网页

时间:2017-12-23 08:53:14

标签: selenium selenium-webdriver sendkeys

我正在尝试使用sendkeys()上传文件 但是selenium webdriver测试失败并出现错误:

"The element is not yet visible: By.xpath: //input[@id='upload-file-pc']"

这是html:

<input id="upload-file-pc" class="file-field-input" type="file" onchange="return validateFileSelected(this);" name="upload-file-pc"/>
<a class="dropbox-dropin-btn dropbox-dropin-default file-field-link" href="Javascript:void(0);">
<span class="dropin-btn-status"/>
Choose from Computer
</a>

代码:

    String fileLocation = CommonConstants.TEST_FILE_LOCATION + this.config.getString("simpletext");
        logger.info("text file location: {}", fileLocation);
        WebExecutionHelper.waitForElementVisible(driver, By.xpath("//input[@type='file']")).sendKeys(fileLocation); 

上传按钮图片:

请帮忙

2 个答案:

答案 0 :(得分:1)

Selenium可能不会对隐藏元素进行操作。您可以做的是强制它显示executeScript

// get <input> element
input = driver.findElementById("upload-file-pc")

// make it visible
driver.executeScript(`
    var input = arguments[0];
    input.className = '';
    input.style.display = 'block';
    input.style.position = 'fixed';
    input.style.bottom = 0;
    input.style.left = 0;
    `, input)

// set the file
input.sendKeys(fileLocation)

答案 1 :(得分:0)

Selenium无法在隐形元素上运行(例如sendKeys,click)。

您可以通过executeScript在backgroud中发送上传文件的绝对路径。

Java示例:

    WebElement fileUpload = driver.findElement(By.css("#upload-file-pc"));
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("return arguments[0].value=arguments[1];", fileUpload);