2017-02-15 92 views
-1
 List<IWebElement> shittyBiz = new List<IWebElement>(); 
     var myEles = driverGC.FindElements(By.CssSelector("div.search-result")); 
     for (int i = 0;i<=1000;i++){ 
      myEles = driverGC.FindElements(By.CssSelector("div.search-result")); 
      foreach (IWebElement business in myEles) 
      { 
       driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); 
       var starRating = " "; 
       try 
       { 
        starRating = business.FindElement(By.CssSelector("div.biz-rating > div.i-stars")).GetAttribute("title"); 
       } 
       catch (OpenQA.Selenium.NoSuchElementException) 
       { 
        MessageBox.Show("No stars"); 
        continue; 
       } 
       starRating = Regex.Replace(starRating, @"[A-Za-z\s]", string.Empty); 
       float stars = float.Parse(starRating); 
       MessageBox.Show(stars.ToString()); 

       if (stars <= 3) 
       { 
        //shittyBiz.Add(starRating); 
        MessageBox.Show("Shitty"); 
        driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); 
        var bizName = business.FindElement(By.CssSelector(".biz-name")); 
        MessageBox.Show(bizName.Text); 
        shittyBiz.Add(bizName); 
        var bizLocation = business.FindElement(By.CssSelector(".secondary-attributes")); 
        MessageBox.Show(bizLocation.Text); 
        shittyBiz.Add(bizLocation); 
       } 
       else 
       { 
        driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); 
        MessageBox.Show("Too good"); 
       } 

      } 
      try 
      { 
       driverGC.FindElement(By.CssSelector("div.arrange_unit > a.u-decoration-none")).Click(); 
       continue; 
      } 
      catch (OpenQA.Selenium.NoSuchElementException) 
      { 
       MessageBox.Show("No more pages"); 
       return; 
       //driverGC.Quit(); 
      } 
     } 

我可以讓程序運行正常第一次,但它使用了在嘗試結束後,要到下一個頁面,我得到的StaleElementReferenceException在第一次嘗試中幾乎立即在starRating上發生錯誤。我嘗試了所有我能想到的,但不知道爲什麼它會拋出我的錯誤。循環沒有找到元素

回答

0

當DOM刷新或更改時,驅動程序會丟失先前所在的所有元素。移至新頁面myEles後無效,因此當您嘗試使用它來定位另一個元素時,您在business上獲得StaleElementReferenceException。解決的辦法是找到myEles每次迭代並繼續使用索引的位置,for

int size = 1; 
for (int i = 0; i < size; ++i) 
{ 
    var myEles = driverGC.FindElements(By.CssSelector("div.search-result")); 
    size = myEles.Count(); 

    driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); 
    var starRating = " "; 
    try 
    { 
     starRating = myEles[i].FindElement(By.CssSelector("div.biz-rating > div.i-stars")).GetAttribute("title"); 
    } 

    //... 

    // and don't forget to go back 
    driver.Navigate().Back(); 
} 
+0

不知道爲什麼,但是這並沒有工作,它並沒有給我一個不同的值,每個元素和我仍然得到陳舊錯誤時我去下一頁。 –

+0

@JustinKowalsky你可以發佈你的新代碼嗎?你究竟在哪裏得到例外? – Guy

+0

不確定如何正確發佈代碼,所以繼承了粘貼bin。 http://pastebin.com/jJk1hWCw當我運行代碼時,它第一次運行良好。然後到達第88行,點擊下一個按鈕,然後返回到頂部,在那裏我立即捕獲StaleElementReferenceException,然後它會一遍又一遍地重複錯誤,但是需要繼續並轉到下一頁。 –