由于输入类型=文件在网页上不可见,因此通过sendkeys()上传文件失败

问题描述 投票:0回答:2

我正在尝试使用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); 

上传按钮图片:

请帮忙

selenium selenium-webdriver sendkeys
2个回答
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)

0
投票

Selenium无法在不可见元素上运行(例如sendKeys,click)。

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

Java示例:

    WebElement fileUpload = driver.findElement(By.css("#upload-file-pc"));
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("return arguments[0].value=arguments[1];", fileUpload);
© www.soinside.com 2019 - 2024. All rights reserved.