C# 读取网页上的Table

 WebBrowser web = new WebBrowser();

 DataTable dt = new Datable();
        private void button1_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Count==0)
            {
                HtmlDocument doc = web.Document;
                dt.Columns.Add("开奖日期", System.Type.GetType("System.String"));
                dt.Columns.Add("期号", System.Type.GetType("System.String"));
                dt.Columns.Add("开奖号", System.Type.GetType("System.String"));
                dt.Columns.Add("试机号", System.Type.GetType("System.String"));

                HtmlElementCollection tbs = doc.GetElementsByTagName("TABLE");
                foreach (HtmlElement tb in tbs)
                {
                    HtmlElementCollection trs = tb.GetElementsByTagName("TR");
                    foreach (HtmlElement tr in trs)
                    {
                        HtmlElementCollection tds = tr.GetElementsByTagName("TD");
                        if (tds.Count > 0)
                        {
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < tds.Count; i++)
                            {

                                dr["开奖日期"] = tds[0].InnerText;
                                dr["期号"] = tds[1].InnerText;
                                dr["开奖号"] = tds[2].InnerText;
                                dr["试机号"] = tds[3].InnerText;

                            }
                            dt.Rows.Add(dr);
                        }
                    }
                }
            }
          
            this.dataGridView1.DataSource = dt;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            web.Url = new System.Uri("http://www.52cp.cn/toolset/index.php/History/fuc3d");

        }

你可能感兴趣的:(C# 读取网页上的Table)