2012-11-23 159 views
1

我是硒和網絡驅動程序的新手。我的問題很簡單。對不起,如果你發現這個非常基本的問題。 我正在使用Visual Studio 2010終極與硒2和使用語言C#與瀏覽器IE 9.我試圖執行下面的簡單代碼。硒網絡驅動程序,C#

IWebDriver driver = new InternetExplorerDriver(@"D:\IEDriverServer\"); 
driver.Navigate().GoToUrl("http://www.google.com"); 


System.Console.WriteLine("Page title is: " + driver.Title); 

Console.WriteLine(driver.Title); 
Console.WriteLine("Waiting to find element"); 

IWebElement returnedValue = driver.FindElement(By.Name("q")); 

Console.WriteLine("Element Found"); 

上面的代碼拋出Unable to find the element with name==... 我認爲這可能會在瀏覽器加載問題。瀏覽器不能完全加載,因此導致它顯示錯誤。然後,我在driver.navigate行後面添加下面的代碼,使其等待瀏覽器完全加載。

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); 
wait.Until(ExpectedConditions.TitleIs("Google")); 

奇怪的是,它再次忽略此webdriverwait線,並直接跳轉到導致顯示未找到錯誤元素「wait.until」行。我該怎麼辦。我在這裏錯過了什麼?

+0

我不使用C#硒,但它不應該是'driver.FindElementByName(「Q」)'這是怎麼回事在python中。 – bobthemac

+0

谷歌網站是否被加載? –

回答

1

嘗試設置隱含等待driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

根據Selenium documentation這是默認情況下0 - 也就是說,如果沒有立即找到該元素,Selenium將拋出「無法找到元素...」錯誤。

0

變化wait.Until(ExpectedConditions.TitleIs("Google"));

wait.Until(ExpectedConditions.visibilityOfElementLocated(By.name("q")))

有可能是頁面的標題已改爲谷歌,但完整的頁面沒有完全加載

2

你幾乎就在確定的情況下等待...但在C#中有不同的方式來使Webdriver等待,直到元素可見,直到頁面加載。

 WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); 
     IWebElement myDynamicElement = wait.Until<IWebElement>((d) => 
     { 
      return d.FindElement(By.Name("q")); 
     }); 

希望這有助於...所有的最好的朋友:)