2014-10-29 37 views
2

我使用C#.NET 4和Selenium WebDriver 2.44.0.0和chromeDriver。 當它無法找到元素,硒拋出錯誤:C#如何從NoSuchElementException獲取方法和選擇器

no such element 
(Session info: chrome=38.0.2125.104) 
(Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64) 


但我想知道哪些元素是缺少。我看到一些文章說,它可以顯示這樣的細節:

OpenQA.Selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"hello"} 


誰能告訴我怎麼去從NoSuchElementException異常的方法和選擇?


這裏是我的代碼

try 
{ 
    for(int i=0; i<10; i++) 
    { 
      string className = "items-" + i; 
      IWebElement t = Driver.FindElement(By.CssSelector("[class$='" + className + "'] > span")); 
      t.Click(); 
    } 
} 
catch (NoSuchElementException ex) 
{ 
    Logger.Error("Error: " + ex.Message); 
    Debug.WriteLine(ex.Message); 
} 
+0

你真的應該避免「例外編碼」。例外情況應該是特例 - 例如硬盤空間不足或網絡連接失敗。如果你正在編寫代碼,並希望你的代碼能夠「正常」工作,那麼你做錯了什麼。 – Enigmativity 2014-10-31 06:42:17

回答

1

By定位器的.ToString()方法返回所要求的內容。

據我所知,異常本身不包含信息。但是,處理異常並將其與在拋出它的FindElement()方法中使用的定位器函數相關聯是非常直接的。

例如,如果在第5次迭代的元素不能被發現,下面的代碼會產生此消息

Error: no such element

Error: Unable to find element using function By.CssSelector: [class$='items-4'] > span

By locator;  // need to declare this outside the scope of the try block 
       // so it can be accessed in the catch block 
try 
{ 
    for(int i=0; i<10; i++) 
    { 
      string className = "items-" + i; 
      locatorFunction = By.CssSelector("[class$='" + className + "'] > span") 
      IWebElement t = Driver.FindElement(locatorFunction); 
      t.Click(); 
    } 
} 
catch (NoSuchElementException ex) 
{ 
    Logger.Error("Error: " + ex.Message); 
    Logger.Error("Error: Unable to find element using function " + locatorFunction.ToString()); 
} 
+0

感謝您的回答。但我想避免修改當前腳本。是否可以配置Selenium在異常消息中顯示更多詳細信息? – Buaban 2014-10-30 03:54:23

+0

除了消息之外,您還可以選擇獲取StackTrace。你還在尋找哪些其他信息? – Saifur 2014-10-30 13:02:13

+0

我不認爲有任何Selenium異常的配置選項。我在回答中添加了一段,以明確這是一種將信息與異常關聯的方式,而不是從異常本身中提取信息。 – 2014-10-30 15:42:34

1

參考硒API文檔的.NET發現here。 但是,我不認爲它會給你想要的異常跟蹤方面。打印您正在使用的選擇器,可以幫助您識別拋出錯誤的元素

+0

謝謝。我將使用來自John O的解決方法。 – Buaban 2014-10-30 03:49:34