2013-06-20 53 views
1

我正在測試的應用程序有大量需要不斷解析的表。我目前使用的方法是非常大的錶慢,所以我想我可以嘗試多線程,並獲得這些要素simutaniusly是否可以從WebDriver實例同時獲取頁面上的多個元素?

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(驅動程序);

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 

在此先感謝!

+0

你不應該這樣做。 ['WebDriver'不是線程安全的](https://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Is_WebDriver_thread-safe?)所以這肯定會導致瘋狂的不可預知的行爲。 – acdcjunior

+0

好的,所以更好的方法可能是嘗試減少css選擇器獲取表格的時間?是否有可能對driver.getPageSource進行保存,然後解析表,然後以某種方式使用'findElements(By.cssSelector());'來解析頁面源代碼? – bbarke

+0

'慢'有多慢?這是*所有*你正在使用的代碼,哪部分是慢? – Arran

回答

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

相關問題