一、問題點:
1、模擬登錄后,如果帶有嵌套的iframe嵌套,不好讀取iframe內容,可以直接指定iframe抓取網址
2、C# 清除WebBrowser控件的Session和Cookie
參考文檔:http://www.360doc.com/content/14/0810/12/9200790_400769010.shtml
代碼如下:
[DllImport("wininet.dll",SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); private void timer_Tick(object sender, EventArgs e) { InternetSetOption(IntPtr.Zero,42,IntPtr.Zero,0); if (this.webBrowser.Document != null) { this.webBrowser.Document.Cookie.Remove(0, this.webBrowser.Document.Cookie.Count() - 1); } string[] cookies = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Cookies)); foreach (string currentFile in cookies) { try { System.IO.File.Delete(currentFile); } catch { } } this.webBrowser.Navigate(SysInfo.WEBURL); }
3、IHTMLDocument2 的引用 引用--COM--Microsoft HTML Object Library
二、模擬登錄
模擬無驗證碼登錄,用WebBrowser比較簡單,為登錄用戶和密碼賦值,然后模擬點擊登錄按鈕即可
this.webBrowser.Document.GetElementById("user").SetAttribute("value", "user"); this.webBrowser.Document.GetElementById("password").SetAttribute("value", "password"); this.webBrowser.Document.InvokeScript("SetCookie"); for (int i = 0; i < 10; i++)//等待1秒,進行登錄 { Thread.Sleep(100); } HtmlElement btnLogin = this.webBrowser.Document.GetElementById("login"); btnLogin.InvokeMember("Click"); for (int i = 0; i < 5; i++)//等待0.5秒,進行跳轉 { Thread.Sleep(100); } this.webBrowser.Navigate(SysInfo.DATAURL);
三、抓取數據
指定抓取網址,載入之后,獲取元素值
HtmlElement div = this.webBrowser.Document.GetElementById("style1");
參考博客:C#中的WebBrowser控件的使用