C# WebBroswer读取html页面元素

前面的几个示例都 是对页面中的某一控件进行读取,而有时有些页面没有input控件,而只有一些常用页面元素,对于这样的页面读取就要换一种方式了:

这里就要用到HtmlDocument中的GetElementsByTagName方法,如果我们要读取某一页面中的第一个<a></a>可以这样使用:doc.GetElementsByTagName("a")[0];后面的就是索引的设定了;用的多了也就不觉得有什么内容了,直接上代码(电信的号码查询):

代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Web;


namespace 电信查询
{
    
public partial class Form1 : Form
    {
        
//WebService引用
        private objTele.Service1SoapClient objtele = new 电信查询.objTele.Service1SoapClient();
        
//当前查询号码
        private string nowtnum = "";
        
//当前查询ID
        private string nowtid = "";
        
//当前用户余额
        private string nowtmoney = "";

        
//当前用户名称
        private string nowtname = "";

        
//上一个用户名
        private string oldtname = "";
        
//上一个查询号码
        private string oldtnum = "";
        
//上一个查询ID
        private string oldtid = "";
        
//上一用户余额
        private string oldtmoney = "";
        
//刷新页面次数
        private int islock = 0;
        
public Form1()
        {
            InitializeComponent();
        }

        
private void tspstart_Click(object sender, EventArgs e)
        {
            
if (cbbtime.Text != "")
            {
                
if (tspstart.Text == "开始查询")
                {
                    timer1.Interval 
= Convert.ToInt32(cbbtime.Text.ToString().Trim());
                    timer1.Enabled 
= true;
                    tspstart.Text 
= "停止查询";
                }
                
else
                {
                    tspstart.Text 
= "开始查询";
                    timer1.Enabled 
= false;
                    timer2.Enabled 
= false;
                }
            }
            
else
            {
                MessageBox.Show(
"请先设定查询时间间隔""错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
return;
            }
        }

        
private void cbbtime_SelectedIndexChanged(object sender, EventArgs e)
        {
            
if (cbbtime.Text != "")
            {
                timer1.Interval 
= Convert.ToInt32(cbbtime.Text.ToString().Trim());
            }
        }

        
private void Form1_Load(object sender, EventArgs e)
        {
            webpage.Url 
= new Uri("http://www.1065921611.com/");
            lvorder.Columns.Add(
"编号"40);
            lvorder.Columns.Add(
"号码"80);
            lvorder.Columns.Add(
"姓名"80);
            lvorder.Columns.Add(
"用户余额"80);
            lvorder.Columns.Add(
"状态"120);
            lvorder.Columns.Add(
"时间"120);
            lvorder.GridLines 
= true//显示表格线
            lvorder.View = View.Details;//显示表格细节
            lvorder.HeaderStyle = ColumnHeaderStyle.Clickable;//对表头进行设置
            lvorder.FullRowSelect = true;//是否可以选择行
            cbbtime.Text = "5000";
            
this.Text = "电信查询";
        }

        
private void timer1_Tick(object sender, EventArgs e)
        {
            
string strtele = "";
            
try
            {
                
//从数据库中查询一条等待查询的数据
                strtele = objtele.selectOneSelectStratMobile(Encrypt(), "2");
                
if (strtele != "")
                {
                    
string[] stroder = strtele.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                    
if (stroder[0!= "0" && stroder[1!= "0")
                    {
                        
try
                        {
                            HtmlDocument doc 
= webpage.Document.Window.Frames[1].Document.Window.Frames[3].Document.Window.Frames[0].Document;
                            HtmlElement telenum 
= doc.All["chargePhone"];
                            HtmlElement submit 
= doc.GetElementsByTagName("a")[0];
                            nowtid 
= stroder[0].ToString().Trim();
                            nowtnum 
= stroder[1].ToString().Trim();
                            nowdo.Text 
= "正在查询用户:" + nowtnum.ToString() + "信息";
                            
if (telenum == null || submit == null)
                            {
                                nowdo.Text 
= "网络受阻查询用户:" + nowtnum.ToString() + "信息失败";
                                databind(nowtid.ToString(), nowtnum.ToString(), 
"查询失败""0""网络受阻,查询失败"9);
                                
return;
                            }
                            telenum.SetAttribute(
"value", stroder[1].ToString());
                            submit.InvokeMember(
"click");
                            timer1.Enabled 
= false;
                            timer2.Enabled 
= true;
                            timer2.Interval 
= 2000;
                            islock 
= 0;
                        }
                        
catch (Exception)
                        {
                            
return;
                        }
                    }
                }
            }
            
catch (Exception)
            {

                
throw;
            }
        }

        
//页面加载完成时发生
        private void webpage_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
        
//页面开始刷新时执行
        private void webpage_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {

        }

        
/// <summary> 
        
/// 加密数据 
        
/// </summary> 
        
/// <returns></returns> 
        public static string Encrypt()
        {
            
string Text = "asuygp834p8934g8ye893rehfvasu78698734r";
            
string sKey = "as4564656uygp834p893";
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
            
byte[] inputByteArray;
            inputByteArray 
= Encoding.Default.GetBytes(Text);
            des.Key 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            des.IV 
= ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(08));
            System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
            CryptoStream cs 
= new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 
0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret 
= new StringBuilder();
            
foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat(
"{0:X2}", b);
            }
            
return ret.ToString();
        }

        
private void timer2_Tick(object sender, EventArgs e)
        {

            
if (islock < 10 && !timer1.Enabled)
            {
                
if (islock == 0 ||islock==3||islock==6)
                {
                    
try
                    {
                        HtmlDocument doc 
= webpage.Document.Window.Frames[1].Document.Window.Frames[3].Document.Window.Frames[1].Document;
                        HtmlElement subref 
= doc.GetElementsByTagName("a")[0];
                        
if (subref == null)
                        {
                            HtmlDocument doc1 
= webpage.Document.Window.Frames[1].Document.Window.Frames[3].Document.Window.Frames[1].Document;
                            subref 
= doc1.GetElementsByTagName("a")[0];
                        }
                        subref.InvokeMember(
"click");
                    }
                    
catch (Exception)
                    {
                        
return;
                    }
                }
                
else
                {
                    
try
                    {
                        HtmlDocument doc 
= webpage.Document.Window.Frames[1].Document.Window.Frames[3].Document.Window.Frames[1].Document;
                        
string userresult = doc.GetElementsByTagName("div")[6].GetElementsByTagName("ol")[0].InnerText.ToString();
                        
string[] userinfo = userresult.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        
if (userinfo.Length == 4)
                        {
                            
if (userinfo[2].ToString().Trim() == nowtnum.ToString())
                            {
                                timer1.Enabled 
= true;
                                timer2.Enabled 
= false;
                                nowtname 
= userinfo[1].ToString().Trim();
                                nowtmoney 
= userinfo[3].ToString().Trim();
                                oldtid 
= nowtid.ToString();
                                oldtmoney 
= nowtmoney;
                                oldtname 
= nowtname;
                                oldtnum 
= nowtnum;
                                nowdo.Text 
= "查询用户:" + nowtnum.ToString() + "信息成功";
                                databind(nowtid, nowtnum, nowtname, nowtmoney, 
"查询成功"8);
                            }
                        }
                       
                    }
                    
catch (Exception)
                    {
                        islock
++;
                        
return;
                    }
                }
                islock
++;
            }
            
else
            {
                nowdo.Text 
= "查询用户:" + nowtnum.ToString() + "信息失败";
                nowtname 
= "查询失败";
                nowtmoney 
= "0";
                oldtid 
= nowtid.ToString();
                oldtmoney 
= nowtmoney;
                oldtname 
= nowtname;
                oldtnum 
= nowtnum;
                timer1.Enabled 
= true;
                timer2.Enabled 
= false;
                databind(nowtid, nowtnum, 
"无号码信息""0""无响应查询失败"9);
            }
        }
        
/// <summary>
        
/// 联通充值数据信息状态更新
        
/// </summary>
        
/// <param name="ormd"> 信息编号</param>
        
/// <param name="ormn">号码</param>
        
/// <param name="ormoney">金额</param>
        
/// <param name="state">状态</param>
        
/// <param name="n">状态标识</param>
        private void databind(string ormd, string ormn, string name, string money, string state, int n)
        {
            
bool id = false;
            objTele.SelectTelecom sTele 
= new 电信查询.objTele.SelectTelecom();
            sTele.sctId 
= Convert.ToInt32(ormd.Trim());
            sTele.sctName 
= name;
            sTele.sctExecTime 
= DateTime.Now;
            sTele.sctState 
= n;
            sTele.sctRemainAmount 
= Convert.ToDecimal(money.ToString());
            
try
            {
                id 
= objtele.updateOneSelectTelecom(Encrypt(), sTele);
                
if (!id)
                    id 
= objtele.updateOneSelectTelecom(Encrypt(), sTele);

            }
            
catch (Exception)
            {
            }

            ListViewItem[] listViewItem 
= new ListViewItem[1];
            listViewItem[
0= new ListViewItem(new string[] { ormd, ormn, name, money + "", state,DateTime.Now.ToString() });
            lvorder.Items.AddRange(listViewItem);

        }
    }
}

 

 

posted @ 2010-02-04 16:51  古史漫谈  阅读(2972)  评论(0编辑  收藏  举报