使用C#测试网站
伙计们,
我需要完成一些复杂的网络爬行。
简单的目标:登录页面,在某些文本字段中输入一些值,单击“提交”,然后从检索到的页面中提取一些值。
什么是最好的方法?
- 一些unit testing第三方lib?
- 在C#中手动爬行?
- 也许有一个特别准备好的lib?
- 还有其他方法吗?
这需要在Web应用程序中完成。
非常感谢您的帮助。
不确定它在Web应用程序中如何工作,但您是否考虑过尝试使用HtmlUnit ? 我认为它应该工作正常,因为它基本上是一个无头网络浏览器。
Steven Sanderson有一篇关于在.NET代码中使用HtmlUnit的博客文章 。
华廷。
var browser = new IE(); browser.GoTo("http://www.mywebsite.com"); browser.TextField("username").TypeText("username goes here"); // alternatively, use .Value = if you don't need to simulate keystrokes. browser.Button(Find.ById("submitButton")).Click();
并在返回页面的断言中:
Assert.AreEqual("You are logged in as Username.", ie.TextField("username").Value); // you can essentially check any HTML tag, I just used TextField for brevity.
编辑 –
在Web浏览器中阅读编辑后,您可以考虑使用WebRequest和HTML Agility Pack来validation您获得的内容:
WebRequest的:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
HTML敏捷包:
如何使用HTML Agility包
我打算说Selenium,但如果你打算在内部做,我可能会做一些类似NUnit的事情来编写测试,然后从web-app运行它们。
为什么在网络应用程序中呢? 这就像在车内碰撞测试汽车一样。
如果您正在寻找更轻量级的东西,请尝试使用.Net的SimpleBrowser – 在Github上开源。
没有提到惊讶的HTMLAgilityPack。 这是迄今为止最简单的使用方法。
使用C#和Xpath抓取网站
如果您知道表单值应该进入和出现的内容,您可以在C#中创建一个使用HttpWebRequest并发布到页面并解析结果的应用程序。 这段代码非常适合我自己使用,但你应该能够调整它并使它做你想做的事情。 它实际上是一个更大的类的一部分,它允许您向其添加post / get项目,然后为您提交http请求。
// this is for the query string char[] temp = new char[1]; temp[0] = '?'; // create the query string for post/get types Uri uri = _type == PostType.Post ? new Uri( url ) : new Uri( ( url + "?" + postData ).TrimEnd( temp ) ); // create the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create( uri ); request.Accept = _accept; request.ContentType = _contentType; request.Method = _type == PostType.Post ? "POST" : "GET"; request.CookieContainer = _cookieContainer; request.Referer = _referer; request.AllowAutoRedirect = _allowRedirect; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3"; // set the timeout to a big value like 2 minutes request.Timeout = 120000; // set our credentials request.Credentials = CredentialCache.DefaultCredentials; // if we have a proxy set its creds as well if( request.Proxy != null ) { request.Proxy.Credentials = CredentialCache.DefaultCredentials; } // append post items if we need to if( !String.IsNullOrEmpty( _body ) ) { using( StreamWriter sw = new StreamWriter( request.GetRequestStream(), Encoding.ASCII ) ) { sw.Write( _body ); } } if( _type == PostType.Post && String.IsNullOrEmpty( _body ) ) { using( Stream writeStream = request.GetRequestStream() ) { UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes( postData ); writeStream.Write( bytes, 0, bytes.Length ); } } if( _headers.Count > 0 ) { request.Headers.Add( _headers ); }//end if // we want to keep this open for a bit using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() ) { // TODO: do something with the response }//end using