1

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

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

提前致谢!

4

1 回答 1

0

Just adding to @acdcjunior's comment that the WebDriver class is not thread safe; I've found the following issue which I believe is related to this question: Issue 6592: IE Driver returns 404: File not found

If it is the same issue you're having, then one solution is to synchronise your calls the WebDriver. I solved this by creating a SynchronizedInternetExplorerDriver.java class, which synchronises calls to the underlying WebDriver.

Let me know if this helps (using this SynchronizedInternetExplorerDriver, you'll (at least) be able to rule out thread issues as the cause).

Code Snippet:

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);
        }
    }

...

}

Full Code: SynchronizedInternetExplorerDriver.java

于 2014-08-25T00:48:24.433 回答