[旧帖]
[原创][申请邀请码] 和讯博客自动留言之WebBrowser方法
0.00雪花
发表于:
2009-11-17 09:42
1743
[旧帖] [原创][申请邀请码] 和讯博客自动留言之WebBrowser方法
0.00雪花
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using Functions; using System.IO; using System.Web; using System.Xml; using System.Collections; using System.Threading; using mshtml; namespace HexunBlog { public partial class FormWebBrowser : Form { public FormWebBrowser() { InitializeComponent(); } private static CookieContainer _ReqCookies = new CookieContainer(); /// <summary> /// 请求Cookies /// </summary> public static CookieContainer ReqCookies { get { if (_ReqCookies == null) { _ReqCookies = new CookieContainer(); } return _ReqCookies; } set { _ReqCookies = value; } } public string _cookieStr; public string cookieStr { get { return _cookieStr; } set { _cookieStr = value; } } public string LastUrl { get { return _LastUrl; } set { _LastUrl = value; } } private string _LastUrl; private int _ID; public int ID { get { return _ID; } set { _ID = value; } } private string _UserIDList; public string User_IDList { get { return _UserIDList; } set { _UserIDList = value; } } private string _User_NameList; public string User_NameList { get { return _User_NameList; } set { _User_NameList = value; } } private static DataTable _dtUserURLList = new DataTable(); public static DataTable dtUserURLList { get { return _dtUserURLList; } set { _dtUserURLList = value; } } System.Threading.AutoResetEvent obj = new System.Threading.AutoResetEvent(false); private void FormWebBrowser_Load(object sender, EventArgs e) { // this.myWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); } public void btnSubmit_Click(object sender, EventArgs e) { //主线程 dtUserURLList.Clear(); myWebBrowser.ScriptErrorsSuppressed = true; myWebBrowser.Navigate("http://reg.hexun.com/login.aspx?username=" + TextBoxUserName.Text + "&password=" + TextBoxPassword.Text + ""); this.myWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); obj.Reset(); while (obj.WaitOne(100, false) == false) { Application.DoEvents(); } //WaitOne 在子程序执行Set才继续执行循环 if ((cookieStr != "" || cookieStr != null) & myWebBrowser.Document.Url.ToString().Contains("http://i.hexun.com/")) { string[] UserIDString = cookieStr.Split("=;%".ToCharArray()); string FriendsUserIDData = string.Empty; for (int i = 0; i < UserIDString.Length; i++) { if (UserIDString.Equals(" userToken")) { FriendsUserIDData = WebRequestMethods.ReGetHtml("http://message.hexun.com/GetFriends.aspx?id=" + Convert.ToInt32(UserIDString[i + 1]) + ""); // FriendsUserIDData = WebRequestMethods.ReGetHtml("http://"+ Convert.ToInt32(UserIDString[i + 1]) +".blog.hexun.com/"); break; } } string[] UserIDData = FriendsUserIDData.Split("\r\n=;".ToCharArray()); User_IDList = UserIDData[3].ToString(); User_NameList = UserIDData[7].ToString(); dgvFriendList_DataBind(User_IDList, User_NameList); } } private void button1_Click(object sender, EventArgs e) { //主线程 myWebBrowser.ScriptErrorsSuppressed = true; foreach (DataRow dr in dtUserURLList.Rows) { //string PostMethod= WebRequestMethods.PostWebRequestContext(richTextBox2.Text.ToString(), dr["好友ID"].ToString(), dr["用户名"].ToString(), cookieStr); this.myWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); this.myWebBrowser.Navigate(dr["个人主页"].ToString()); obj.Reset(); while (obj.WaitOne(100, false) == false) { try { Application.DoEvents();//重新绘制窗体 } catch (System.Exception ex) { Thread.Sleep(2050); break; } } } //obj.Close(); MessageBox.Show("全部好友留言完毕!"); // myWebBrowser.Dispose(); } private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { // 子线程 //HtmlDocument hd = myWebBrowser.Document.Window.Frames[0].Document; //IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow; //string s = @"function confirm() {"; //s += @"return true;"; //s += @"}"; //s += @"function alert() {}"; //win.execScript(s, "javascript"); cookieStr = myWebBrowser.Document.Cookie; if (LastUrl != myWebBrowser.Document.Url.ToString() && myWebBrowser.Document.Url.ToString().Contains("messageboard.html")) { LastUrl = myWebBrowser.Document.Url.ToString(); HtmlElement btnSubmit = myWebBrowser.Document.All["MbSubmit"]; HtmlElement txtContent = myWebBrowser.Document.All["txtcontent"]; if (txtContent == null || btnSubmit == null) return; txtContent.SetAttribute("value", richTextBox2.Text); try { btnSubmit.InvokeMember("onclick"); } catch (System.Exception ex) { Thread.Sleep(2050); return; } } obj.Set(); myWebBrowser.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); } /// <summary> /// 绑定 /// </summary> /// <param name="pFriendsUserIDList">好友ID</param> /// <param name="pFriendsUserNameList">用户名</param> private void dgvFriendList_DataBind(string pFriendsUserIDList, string pFriendsUserNameList) { char[] charsToTrim = { '"', ' ', '\'' }; string FriendsUserIDList = pFriendsUserIDList.Trim(charsToTrim); string FriendsUserNameList = pFriendsUserNameList.Trim(charsToTrim); DataGridView.CheckForIllegalCrossThreadCalls = false; dgvFriendList.BackgroundColor = Color.White; dgvFriendList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dgvFriendList.DataSource = StringToDataTable(FriendsUserIDList, FriendsUserNameList); dgvFriendList.Columns["好友ID"].Width = 100; dgvFriendList.Columns["用户名"].Width = 100; dgvFriendList.Columns["个人主页"].DataPropertyName = "个人主页"; dgvFriendList.Columns["个人主页"].SortMode = DataGridViewColumnSortMode.NotSortable; dgvFriendList.Columns["个人主页"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } /// <summary> /// 分割 /// </summary> /// <param name="FriendsUserIDList">好友ID</param> /// <param name="FriendsUserNameList">用户名</param> /// <returns></returns> public static DataTable StringToDataTable(string FriendsUserIDList, string FriendsUserNameList) { if (((System.Data.InternalDataCollectionBase)(dtUserURLList.Columns)).Count == 0) { dtUserURLList.Columns.Add("好友ID", typeof(int)); dtUserURLList.Columns.Add("用户名", typeof(string)); dtUserURLList.Columns.Add("个人主页", typeof(string));//缺省的 } string[] sArrayIDList = FriendsUserIDList.Split(',');//分割后分别存到sArray数组里,下面语句读出 string[] sArrayNameList = FriendsUserNameList.Split(','); string[] sArrayUrl = new string[sArrayIDList.Length]; for (int j = 0; j < sArrayIDList.Length; j++) { sArrayUrl[j] = "http://hexun.com/" + sArrayIDList[j].ToString() + "/messageboard.html"; // sArrayUrl[j] ="http://i.hexun.com/home.aspx?id=" + sArrayIDList[j].ToString(); } for (int m = 0; m < sArrayIDList.Length; m++) { if (Convert.ToString(sArrayIDList[m]) != "") { dtUserURLList.Rows.Add(new object[] { sArrayIDList[m], sArrayNameList[m], sArrayUrl[m] }); } } return dtUserURLList; } private void FormWebBrowser_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); //obj.Close(); } } }
/// <summary> /// 访问其他页面 /// </summary> /// <param name="strUrl"></param> /// <returns></returns> public static string ReGetHtml(string strUrl) { //第二次请求 HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(strUrl); string cookhead = getrequestauthorization(strUrl); request1.Method = "GET"; request1.Headers.Add("cookie:" + cookhead); request1.KeepAlive = true; request1.AllowAutoRedirect = true; HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse(); Stream stream2 = response1.GetResponseStream();//获得回应的数据流 //将数据流转成 String string result1 = new StreamReader(stream2, Encoding.GetEncoding("gb2312")).ReadToEnd(); return result1; }
模拟登陆过程应该很简单,由WebBrowser自动完成(前提myWebBrowser.Navigate参数组成好就行了),难的就是怎么知道获取所有的好友ID,这个很困难,不过可以通过Fiddler抓包很容易就知道了,这里就是一个页面存放者该ID( GetFriends)下所有好友的ID。
自动留言,虽此留言板是通过JS动态生成的,查看源码没有留言文本框以及提交ID,但通过Ie developer toolbar可以看出此文本框是有ID的,而且WebBrowser可以获取由JS动态生成的这些留言本的所有的ID,可以正常的使用HtmlElement获取Document元素,然后执行OnClick事件提交表单。
此方法还有个就是采用了多线程处理循环事件,因为我们提交表单,需要在WebBrowser成功加载完才能执行。
System.Threading.AutoResetEvent obj = new System.Threading.AutoResetEvent(false); public void btnSubmit_Click(object sender, EventArgs e) { obj.Reset(); while (obj.WaitOne(100, false) == false) { Application.DoEvents(); } //WaitOne 在子程序执行Set才继续执行循环 } private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { obj.Set(); }
[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课
上传的附件: