首页 文章

上传照片按钮无法在Selenium Webdriver中使用

提问于
浏览
1

上传照片按钮无法在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

5 回答

  • 1

    这是如何添加文件到上传按钮的示例,不太确定什么是按钮的路径,但您必须找到具有 <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");

    希望这可以帮助,

  • 0

    有几件事:

    1) "Element is not clickable" 错误意味着以某种方式覆盖了上传按钮 . 这可能是它被禁用,在一些封面后面,或者我最喜欢的,整个页面清除div . 确保您尝试单击的按钮真正可用于单击...

    2)要使 .sendKeys() 工作,您需要指向 <input type="file"> 元素 . 根据变量名称,您试图指向 <button> webelement .

  • 0

    根据您获得的错误,尝试通过以下任何一个解决它,替换click事件:

    Actions act = new Actions(wd);
    act.moveToElement("Your Webelement").click().perform();
    

    或者您可以使用JavaScript功能,

    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].click();", "Your Webelement");
    
  • 0

    你需要' type ' your file into the input element. Your above send keys command isn' t非常正确 .

    您可以尝试的代码:

    driver.findElement(By.xpath("//input[@name="image"]")).sendKeys("Image Path Here") ;
    
  • 2

    我的回答在一篇SO帖子中被@ JimEvans 批评,他是 Selenium web automation framework 的核心撰稿人 . 我从他身上学到了一些东西这就是他对 <input type="file"> 上传按钮的看法 .

    如果您尝试上传文件,并且相关页面使用HTML提供的标准上传机制,您可以直接使用Selenium本身 . 标准HTML机制带有 <input type="file"> 元素 . 一旦在页面上找到了文件上传元素,就可以使用 element.sendKeys("full/path/and/file/name/here"); . 这在Element Send Keys command of the W3C WebDriver Specification的算法的步骤10中记录,并在Selenium项目的测试代码example中的几个文件上载测试中使用 .

相关问题