A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© aisini 金牌黑马   /  2014-8-21 15:05  /  1018 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. using System;
  2. using System.Windows.Forms;

  3. namespace YingFeng.TraderHandle
  4. {
  5.     public class AsynWebRequest
  6.     {
  7.         public Uri URL { get; set; }
  8.         private WebBrowser browser;

  9.         public AsynWebRequest(string url)
  10.         {
  11.             this.URL = new Uri(url);
  12.         }
  13.         public void Navigate()
  14.         {
  15.             if (this.URL == null)
  16.                 throw new Exception("URL cannot be empty");
  17.             this.browser = new WebBrowser();
  18.             this.browser.ScriptErrorsSuppressed = true;
  19.             this.browser.DocumentCompleted += (s, e) =>
  20.             {
  21.                 if (e.Url.Equals(this.browser.Url))
  22.                 {
  23.                     RequestCompletedEventArgs arg = new RequestCompletedEventArgs
  24.                     {
  25.                         Document = this.browser.Document
  26.                     };
  27.                     RequestCompleted(s, arg);
  28.                 }
  29.             };
  30.             this.browser.Url = this.URL;
  31.         }
  32.         /// <summary>
  33.         /// 获取具有指定标识符的节点内容
  34.         /// </summary>
  35.         /// <param name="identifier">元素的id或name属性</param>
  36.         /// <returns></returns>
  37.         public string this[string identifier]
  38.         {
  39.             get
  40.             {
  41.                 if (this.RequestCompleted == null)
  42.                 {
  43.                     throw new Exception("The document has not been completely loaded");
  44.                 }
  45.                 return this.browser.Document.GetElementById(identifier).InnerText;
  46.             }
  47.         }

  48.         public delegate void RequestCompletedEventHandler(object sender, RequestCompletedEventArgs e);
  49.         public event RequestCompletedEventHandler RequestCompleted;
  50.         public class RequestCompletedEventArgs
  51.         {
  52.             public HtmlDocument Document { get; set; }
  53.         }
  54.     }
  55. }
  56. 调用示例:
  57. var awr = new AsynWebRequest("http://stockhtm.finance.qq.com/sstock/ggcx/300101.shtml");
  58.             awr.RequestCompleted += (s,a) => {
  59.                 MessageBox.Show(a.Document.GetElementById("main-4").InnerText);
  60.                 MessageBox.Show(awr["main-4"]);
  61.             };
  62.             awr.Navigate();
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马