首页 > 解决方案 > 上传照片按钮在 Selenium Webdriver 中不起作用

问题描述

上传照片按钮在 Selenium Webdriver 中不起作用

我已经厌倦了什么

driver.findElement(uploadPhotoBtn).sendKeys("E:\\photo.png");

也试过这个Robot功能

    driver.findElement(uploadPhotoBtn).click();
    StringSelection ss = new StringSelection(logoPath);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

相同Robot的功能适用于另一个上传按钮,但在此处尝试使用时,.click不起作用,这就是无法使用该Robot功能的原因。

HTML页面来源:

> <div ng-show="!status.uploading" ng-class="{ '!isMobile':
> 'mewe-type-1' }" class="uploader-able !isMobile"><!-- ngIf: isMobile
> --><!-- ngIf: !isMobile --><button ng-if="!isMobile" class="btn-action radius ng-scope">Upload Photo</button><!-- end ngIf: !isMobile
> --><input capture="camera" accept="image/*" name="image" type="file" fileread="fileread" file="file" class="ng-isolate-scope"></div>

控制台日志:

org.openqa.selenium.WebDriverException:未知错误:元素 ... 在点 (314, 477) 处不可点击。其他元素将收到点击:(会话信息:chrome=66.0.3359.181)(驱动程序信息:chromedriver=2.35.528161

标签: javaseleniumselenium-webdriverselenium-chromedriver

解决方案


这是如何将文件添加到上传按钮的示例,不太确定按钮的路径是什么,但是您必须找到带有元素的<input type="file">元素并与之交互:

WebElement uploadPhotoBtn = driver.find(By...); //type="file" 

File file = new File(path);
uploadPhotoBtn.sendKeys(file.getAbsolutePath());

...如果您有某种预览,这就是获取源代码的方法

elementPreview.findElement(By.tagName("img")).getAttribute("src");

希望这可以帮助,


推荐阅读