【问题标题】:Unable to upload file using sendKeys on input element无法在输入元素上使用 sendKeys 上传文件
【发布时间】:2015-01-21 14:13:04
【问题描述】:

为了避免上传文件的窗口对话框,我正在尝试以下操作:

driver.findElement(By.xpath("//span[@class='ab-attachment-item']/input")).sendKeys(filePath);

以下是HTML代码sn-p:

<div class="ab-attachments">
  <span class="ab-attachment-item" ng-hide="isReadOnly()" style="background-color: transparent;">
    <input class="ab-attachment-input ng-isolate-scope firefinder-match" type="file" rx-file-upload="file" accept=".pdf,image/*" style="background-color: transparent;">

但它会导致错误:

org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with

我想确认这个错误是否是因为span标签中的ng-hide="isReadOnly()"

以及如何使用 Selenium WebDriver 本身(使用 JavaScriptExecutor 或其他东西)解决这个问题?

为了处理这个对话框,可以使用 Sikuli、AutoIt 等其他工具;但我想避免这种开销。

【问题讨论】:

    标签: java javascript angularjs selenium selenium-webdriver


    【解决方案1】:

    你应该可以这样做:

    driver.findElement(By.className("ab-attachment-input ng-isolate-scope firefinder-match")).sendKeys(filePath);
    

    如果不尝试添加隐式等待,然后再尝试sendKeys

    Int timeoutInSeconds = 10;
    WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("ab-attachment-input ng-isolate-scope firefinder-match"));
    

    【讨论】:

    • TidusJar,我也试过了,但报错:org.openqa.selenium.TimeoutException: Timed out after 10 seconds waiting for visibility of....
    • 发生这种情况的原因是 WebDriver Wait 找不到该元素。这告诉我你没有正确定位元素。
    • 如果我没有正确定位元素,它不会给出错误:org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with 首先它会给出错误:org.openqa.selenium.NoSuchElementException: Unable to locate element: 只有在找到元素时才会检查元素的可见性.
    • 由于您在与元素交互之前进行了隐式等待,这就是超时的地方。在超时时间 10 秒内找不到元素。
    【解决方案2】:

    //我会使用隐式等待,而是直接调用输入元素

    new WebDriverWait(driver, timeoutInSeconds);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[rx-file-upload='file'][accept=".pdf,image/*"]"))).sendKeys("filePathWithExtension");
    

    【讨论】:

    • Saifur,我也试过了,但报错:org.openqa.selenium.TimeoutException: Timed out after 10 seconds waiting for visibility of....
    • 顺便说一句,这是一个可见元素吗?如果是这样,请使用findelEmens() 查看它返回了多少元素。我怀疑有多个元素,选择器也找不到正确的元素。
    • 这很有道理。 Saifur,我试过了,它返回 1 意味着这是唯一的元素。正如我在问题中提到的那样,可能是因为span 标签中的ng-hide="isReadOnly()" 不可见。
    猜你喜欢
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2015-08-12
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多