我正在測試的應用程序有大量需要不斷解析的表。我目前使用的方法是非常大的錶慢,所以我想我可以嘗試多線程,並獲得這些要素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
在此先感謝!
你不應該這樣做。 ['WebDriver'不是線程安全的](https://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Is_WebDriver_thread-safe?)所以這肯定會導致瘋狂的不可預知的行爲。 – acdcjunior
好的,所以更好的方法可能是嘗試減少css選擇器獲取表格的時間?是否有可能對driver.getPageSource進行保存,然後解析表,然後以某種方式使用'findElements(By.cssSelector());'來解析頁面源代碼? – bbarke
'慢'有多慢?這是*所有*你正在使用的代碼,哪部分是慢? – Arran