java - 在 Java 中使用 selenium 等待元素加载时出现问题

标签 java selenium webdriver

我正在尝试使用 Selenium 在使用 ajax 和/或 jquery 加载的页面上查找 webElement。

似乎无论我做什么,都找不到该元素。

我使用的是 Firefox 20 和 Selenium 2.31.0。

我试图获取的部分有看起来像这样的 html(我使用 firefox 中的检查器工具得到了这个):

 <form id="file_upload" method="post" enctype="multipart/form-data" action="myAction.php">
    <table class="table table-striped">
      <tbody>
        <tr>
          <td>
            <input class="input-file" type="file" name="file"></input>
            <input class="btn btn-primary" type="submit" value="upload"></input>
          </td>
          <td style="text-align:right;"></td>
        </tr>
      </tbody>
    </table>
  </form>

我已经尝试过:

WebDriverWait driverWait = new WebDriverWait(driver, 10000);

WebElement dynamicElement =  driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("file_upload")));

System.out.println(dynamicElement.getText());

我已经尝试过:

WebElement dynamicElement = new FluentWait<WebDriver>(driver).withTimeout(1,  TimeUnit.MINUTES).pollingEvery(1, TimeUnit.SECONDS)
    .ignoring(NoSuchElementException.class).until(ExpectedConditions.visibilityOfElementLocated(By.id("file_upload")));

System.out.println(dynamicElement.getText());

但是我尝试的任何操作都不会找到它,或者无论我给它多少时间来找到该元素都会超时。任何帮助将非常感激。谢谢。

最佳答案

// to make sure you are in the default content
// this is not necessary in the most of the cases
driver.switchTo().defaultContent(); // use only if you are in a frame already

driver.switchto().frame("framename or id");
//driver.switchto().frame(driver.findElement(By.xpath("frame locator")));
//driver.switchto().frame(zero-based frameindex);

// now in the frame
WebDriverWait driverWait = new WebDriverWait(driver, 10000);
WebElement dynamicElement = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("file_upload")));
System.out.println(dynamicElement.getText());

// if you want to get out of all frames back to default content
driver.switchTo().defaultContent();

关于java - 在 Java 中使用 selenium 等待元素加载时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16043531/

相关文章:

具有相同返回类型的 Java 方法重载错误?

python - Selenium - 获取页面中的所有 iframe(甚至是嵌套的)?

javascript - Python Selenium : Unable to click button

selenium - 通过 XPath 相对查找元素

java - 如何创建自己的 TypifiedElement

Selenium :测试 "disable on submit"行为

java - JNA 数组结构指针

Javafx 2 TreeView - 隐藏根项目

java - struts 1 form bean线程安全吗?

selenium - 选择自动化测试工具