我試圖通過一些使用Selenium WebDriver的網頁中的錨點進行爬網。我能想到的方法是將錨定在列表中,並在每次單擊後單擊每個錨點並向後導航。這裏是我的代碼:StaleElementReferenceException在Selenium中導航時WebDriver
WebDriver webDriver=new FirefoxDriver();
webDriver.get(SEARCH_URL);
WebElement form2=webDriver.findElement(By.id("frmMain"));
form2.submit();
System.out.println(webDriver.getCurrentUrl());
List<WebElement>doctorAnchors=webDriver.findElements(By.xpath("//td[@class='data']/a"));
int count=0;
for(WebElement anchr:doctorAnchors){
anchr.click();
System.out.println((count++)+" : "+webDriver.getPageSource().toString());
Thread.sleep(10000);
webDriver.navigate().back();
}
代碼只是經過在錨的第一要素,進行點擊,獲取頁面,但是,當我瀏覽倒退,它提供了:
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 169 milliseconds
我通過各種去stackoverflow的帖子在同一個異常,並意識到它可能是由頁面中的一些JavaScript內容引起的,它似乎也是正確的,因爲頁面url是:http://www.somepage.com/dispatch
是否我去任何錨點。像往常一樣,我可以在由司機打開的網絡瀏覽器中導航。但爲什麼這個webDriver.navigate().back()
失敗?如何在點擊鏈接後導航回來?有沒有一種方法可以保存驅動程序的狀態,並單擊並在點擊後恢復該狀態?
@rahulserver,他在哪裏使用webdriver的多個實例?我只看到一個。 – Arran
@Arran那麼代碼是錯誤的。他需要將驅動程序聲明爲靜態全局變量或傳遞給getElementWithIndex()。我不認爲這會工作,雖然我還沒有嘗試過。 – rahulserver
@rahulserver這通常適用於我和一個工作代碼。我使用TesNG作爲單元測試框架。 –