2017-02-22 101 views
0

我正在尝试使用Selenium的Chrome Webdriver和C#自动登录网站。运行以下代码将引发屏幕截图1和2中列出的错误。我究竟做错了什么?谷歌搜索错误似乎没有显示任何相关的结果。Selenium Chrome Webdriver不能正常工作

using System.Drawing.Imaging; 
using System.IO; 
using OpenQA.Selenium.Chrome; 

namespace WebDriverTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Initialize the Chrome Driver 
      using (var driver = new ChromeDriver()) 
      { 
       // Go to the home page 
       driver.Navigate().GoToUrl("https://twitter.com/");      
       // Get User Name field, Password field and Login Button 
       var userNameField = driver.FindElementById("usr"); 
      } 
     } 
    } 
} 

enter image description here

An unhandled exception of type 'OpenQA.Selenium.WebDriverException' occurred in WebDriver.dll. 
    Additional information: A exception with a null response was thrown 
sending an HTTP request to the remote WebDriver server for 
URL http://localhost:61724/session/cc7bae393b288855ed8169dade774baa/element. 
The status of the exception was ReceiveFailure, and the message was: 
The underlying connection was closed: An unexpected error occurred on a receive. 

enter image description here

+0

我相信这是一个版本不匹配。什么是您使用的铬和铬驱动程序的版本? 我会建议尝试与铬56和最新的铬驱动程序2.28。看起来像57铬可能有一些问题。 –

回答

0

你刚才GoToUrl后等待页面加载:

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

获取不同的错误但类似的结果:在WebDriver.dll中发生未处理的类型为“OpenQA.Selenium.WebDriverException”的异常 其他信息:意外错误。 System.Net.WebException:无法连接到远程服务器---> System.Net.Sockets.SocketException:无法建立连接,因为目标机器主动拒绝它:: 1:62419 –

0

我会等待页面加载。

public static void WaitForElementLoad(By by, int timeoutInSeconds) 
{ 
    if (timeoutInSeconds > 0) 
    { 
     WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeoutInSeconds)); 
     wait.Until(ExpectedConditions.ElementIsVisible(by)); 
    } 
} 

curtosey How to wait for element to load in selenium webdriver?

0

验证您的Chrome和ChromeDriver的版本。请参阅兼容性here。同时检查您的Selenium版本是否过时,但这些类型的错误通常是因为版本兼容性。

作为参考,目前latests:

Chrome 56.0... 
ChromeDriver 2.27 
Selenium WebDriver 3.1.0 
0

很清楚!

页面“http://twitter.com”中没有标识为“usr”的元素。

你在寻找什么? 您正在寻找一个id属性设置为“usr”的页面上的元素,并且没有这样的elememt。例外说它

做检查元素plz