是否可以同时从WebDriver实例获取页面上的多个元素?

时间:2013-06-20 18:53:42

标签: java selenium

我正在测试的应用程序有大量需要不断解析的表。我目前使用的方法对于非常大的表来说很慢,所以我想我可以尝试多线程并获得这些元素simutaniusly

public class TableThread
  implements Runnable
{

  private WebDriver driver;
  private String thread;

  TableThread(WebDriver driver, String thread)
  {
    this.driver = driver;
    this.thread = thread;
  }

  @Override
  public void run()
  {
    getTableRow();
  }

  private String getTableRow()
  {
    System.out.println("start getting elements " + thread);

    WebElement tableElement = driver.findElement(By.className("logo"));
    String href = tableElement.getAttribute("href");
    System.out.println("Table Att: " + thread + " " + href);

    return href;

  }

}

和调用该方法的循环

for (int i = 0; i < 10; i++) {

  ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
  TableThread tableThread = new TableThread(driver, "Thread " + i);
  threadExecutor.execute(tableThread);
  Thread.sleep(50);
}

设置this.driver时的错误= ThreadGuard.protect(driver);

start getting elements
Exception in thread "pool-1-thread-1" org.openqa.selenium.WebDriverException: Thread safety error; this instance of WebDriver was constructed on thread main (id 1) and is being accessed by thread pool-1-thread-1 (id 26)This is not permitted and *will* cause undefined behaviour`

设置this.driver = driver;

时出错
Exception in thread "pool-2-thread-1" org.openqa.selenium.UnsupportedCommandException: Error 404: Not Found
Exception in thread "pool-1-thread-1" java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.lang.String

提前致谢!

1 个答案:

答案 0 :(得分:0)

只是添加@ acdcjunior评论WebDriver类不是线程安全的;我发现以下与此问题相关的问题:Issue 6592: IE Driver returns 404: File not found

如果您遇到同样的问题,那么一种解决方案就是将您的呼叫与WebDriver同步。我通过创建一个SynchronizedInternetExplorerDriver.java类来解决这个问题,该类同步对底层WebDriver的调用。

如果这有帮助,请告诉我(使用此SynchronizedInternetExplorerDriver,您至少可以排除线程问题)。

代码段:

public class SynchronizedInternetExplorerDriver extends InternetExplorerDriver {

...

    @Override
    protected Response execute(String driverCommand, Map<String, ?> parameters) {
        synchronized (getLock()) {
            return super.execute(driverCommand, parameters);
        }
    }

    @Override
    protected Response execute(String command) {
        synchronized (getLock()) {
            return super.execute(command);
        }
    }

...

}

完整代码: SynchronizedInternetExplorerDriver.java