2017-09-16 263 views
0

我想在使用webdriver時從網站獲取一些分數。到目前爲止,我嘗試了XPath,CSS,Classname,但有時它位於該項目中,有時卻不是。Selenium WebDriver - 無法找到元素異常

這是我一直在試圖把它的HTML代碼:

<td class="score" rowspan="6"><span class="p1_home">0</span> - <span class="p1_away">0</span></td>

這是我的代碼(我試過至今):

firstHalf[i] = Driver.FindElement(By.XPath("//*[@id=\"parts\"]/tbody/tr[2]/td[2]")).Text; 

其他版本:

firstHalf[i] = Driver.FindElement(By.CssSelector("#parts > tbody > tr:nth-child(2) > td.score")).Text; 
firstHalf[i] = Driver.FindElement(By.ClassName("score")).Text; 

而且我嘗試了兒童班(在分數班),但結果是一樣的,有時可以找到元素,有時它不能。

有什麼建議嗎?

更新:對於我的代碼,我把一些waitThread.Sleep仍然無法正常工作。

for (int r = 0; r < 10; r++) 
       { 
        try 
        { 
         string d1 = Driver.FindElement(By.XPath("//span[@class='p1_home']")).Text; 
         string d2 = Driver.FindElement(By.XPath("//span[@class='p1_away']")).Text; 
         //firstHalf[i] = firstHalf[i].Replace(" ", ""); 
         firstHalf[i] = d1 + "-" + d2; 
         break; 
        } 
        catch (Exception e) 
        { 
         Thread.Sleep(300); 
         r -= 1; 
         eventCounter++; 
         if (eventCounter == 10) 
         { 
          errorMsg.sendErrMsg(e); 
          //errorMsg.stopProgram(); 
         } 
        } 
       } 
+0

ü要哪個元素定位 – iamsankalp89

+0

@ iamsankalp89我想找到類'score'或子類,這些都是'p1_home'和'p1_away' –

+0

//跨度[@ class ='p1_home']和// span [@ class ='p1_away'] – iamsankalp89

回答

0

好吧,我發現了一個解決方案具有不同做法。我使用父類score來取代兩個特定的類。另外,我刪除了「for loop」「try」「catch」,我用它來一次又一次地找到對象。

爲了我的主循環,我加「嘗試」「捕獲」。當我得到例外時,我減少了循環計數器,關閉了窗口並再次打開。此外,我添加了一些Thread.Sleep爲了不會得到錯誤,因爲網絡驅動程序行爲如此之快,這導致了一個問題。

更新我的代碼的版本:

for (int i = 0;; i < stopLimit.Count; i++) 
{ 
    try 
    { 
      Thread.Sleep(500); 
      string score = Driver.FindElementByCssSelector("#parts > tbody > 
                tr:nth-child(2) > td.score").Text; 
      firstHalf[i] = score.Replace(" ", ""); 
    } 
    catch(Exception) 
    { 
      i--; 
      Thread.Sleep(1500); 
      Driver.SwitchTo().Window(Driver.WindowHandles.Last()); 
      Driver.Close(); 
      Driver.SwitchTo().Window(Driver.WindowHandles.First()); 
    } 
} 
1

您可以使用

//span[@class='p1_home'] 

//span[@class='p1_away'] 
+0

我現在想寫,我會測試程序是否崩潰 –

+0

好吧試着讓我知道會發生什麼 – iamsankalp89

+0

好吧,我試了一下。在第一次運行,它的工作完美,但在第二次運行,它墜毀 –

1

要找到特定類的元素和屬性,你可以使用CSS選擇器。例如:

Driver.FindElement(By.CssSelector(".score[rowspan='6']")).Text; 

在你有困難找到元素可靠,你可能想要得到它後,滿足一定的條件,像這樣的情況:

WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30)); 
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".score[rowspan='6']"))); 
+0

我正在測試其他解決方案。我會讓你知道是否工作或以後 –

+0

這個解決方案根本不工作 –

+0

增加了替代選項,以解決可能的加載時間問題。 – Eugene

相關問題