2016-04-05 42 views
0

在下面的代碼硒的webdriver拋出NoSuchElement異常,然後查找元素時,我打繼續

using System; 
using System.Security.Policy; 
using OpenQA.Selenium; 
using OpenQA.Selenium.Chrome; 
using OpenQA.Selenium.Support; 
using OpenQA.Selenium.Support.PageObjects; 

namespace StackOverflowTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      IWebDriver driver = new ChromeDriver(); 
      driver.Navigate().GoToUrl("http://www.stackoverflow.com"); 
      driver.FindElement(By.LinkText("log in")).Click(); 
      driver.FindElement(By.ClassName("google-login")).Click(); 
      Int16 myInt = 2; //breakpoint goes here. 
      driver.Close(); 
     } 
    } 
} 

硒投擲「NoSuchElement」異常。然後當我點擊繼續時,它會點擊它無法找到的元素。有人可以向我解釋爲什麼發生這種事/我做錯了什麼?

回答

2

可能需要一些時間才能加載元素。您可以使用顯式的等待與ExpectedConditions等待元素

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
wait.Until(ExpectedConditions.ElementIsVisible(By.LinkText("log in"))).Click(); 

或者組隱等待

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); 
+0

我想通了這一點,你發佈它的權利之前。但我正在使用Thread.Sleep(25000)。 WebDriverWait是讓硒等待的首選方法嗎?或者Thread.Sleep會工作嗎? – CryptoJones

+0

我知道這不會被視爲'競賽條件'。當你的應用程序比你的響應者更快行動時,這個定義會是什麼? – CryptoJones

+1

@CryptoJones'Thread.Sleep(25000)'會停止腳本25秒,不計米什麼。 'WebDriverWait'同時等待** up **到25秒以使元素符合條件。如果條件在2秒後滿足,則腳本將在2秒後繼續。 – Guy