2017-04-15 41 views
0

我想搜索亞馬遜上的主題,然後按給定的書籍列表逐個執行特定操作。我做了以下幾點:我無法使用Selenium WebDriver逐一訪問WebElements列表

WebDriver driver= new ChromeDriver(); 
     driver.manage().window().maximize(); 
     driver.get("https://www.amazon.com"); 
     driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Operating System Books"); 
     driver.findElement(By.className("nav-input")).click(); 
     links = driver.findElements(By.className("s-access-detail-page")); //try to cache this 
     for(WebElement link : links) { 
       //System.out.println(String.format(link.getAttribute("href"))); //prints 
       link.click(); 
       //extract reviews and one by one forward to semantic analysis 
       driver.navigate().back(); 
      } 
     } 

但是,這個去第一個鏈接,然後回到列表的頁面。 異常在線程「主」 org.openqa.selenium.StaleElementReferenceException:陳舊元件參考:該程序然後用下面的錯誤終止元件不連接到頁文檔

+0

這是完全正常的,你會有這個例外:'StaleElement'意味着你試圖引用的元素不再處於活動瀏覽器窗口中。考慮到您已導航到某個其他頁面,然後導航回來,前一頁中的任何元素都不應再被激活。您必須重新進行搜索或在新窗口中打開鏈接,以便您的原始窗口在其他瀏覽器選項卡中保持不變。 –

回答

0

StaleElementReferenceExceptionwebElement不再連接到DOM,這通常發生在您離開網頁時導航,然後導航回原始頁面,您嘗試使用之前存儲或捕獲的WebElements

爲了避免這種異常則需要再次確定先前捕獲的元素,你的情況你的代碼應該象下面這樣:

List <WebElement>links = driver.findElements(By.className("s-access-detail-page")); //try to cache this 

     for(int i=0; i< links.size(); i++) { 

      List <WebElement> refLinks = driver.findElements(By.className("s-access-detail-page")); 

      refLinks.get(i).click(); 

      driver.navigate().back(); 

     } 
+0

謝謝。有效。 –

0

錯誤,因爲:你所指的元素不再存在於活動頁面中。試試這個代碼:

 public static void main(String[] args) { 
     WebDriver driver= new ChromeDriver(); 
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    driver.manage().window().maximize(); 
    driver.get("https://www.amazon.com"); 
    driver.findElement(By.id("twotabsearchtextbox")).sendKeys(
      "Operating System Books"); 
    driver.findElement(By.className("nav-input")).click(); 
    List<WebElement> links = driver.findElements(By 
      .className("s-access-detail-page")); 

    for (int i = 0; i < links.size(); i++) { 

     List<WebElement> allLink = driver.findElements(By 
       .className("s-access-detail-page")); 

     allLink.get(i).click(); 



     driver.navigate().back(); 

    } 


} 
相關問題