说明:做了个简单的表单html文件,方便查看效果。附件中:bin\Debug\Test.html
效果示例源码下载(Vs 2008)
01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05 using System.Windows.Forms;//
06
07 namespace WebBrowser网页操作
08 {
09 public class Element
10 {
11
12 //根据Name获取元素
13 public HtmlElement GetElement_Name(WebBrowser wb,string Name)
14 {
15 HtmlElement e = wb.Document.All[Name];
16 return e;
17 }
18
19 //根据Id获取元素
20 public HtmlElement GetElement_Id(WebBrowser wb, string id)
21 {
22 HtmlElement e = wb.Document.GetElementById(id);
23 return e;
24 }
25
26 //根据Index获取元素
27 public HtmlElement GetElement_Index(WebBrowser wb,int index)
28 {
29 HtmlElement e = wb.Document.All[index];
30 return e;
31 }
32
33 //获取form表单名name,返回表单
34 public HtmlElement GetElement_Form(WebBrowser wb,string form_name)
35 {
36 HtmlElement e = wb.Document.Forms[form_name];
37 return e;
38 }
39
40
41 //设置元素value属性的值
42 public void Write_value(HtmlElement e,string value)
43 {
44 e.SetAttribute("value", value);
45 }
46
47 //执行元素的方法,如:click,submit(需Form表单名)等
48 public void Btn_click(HtmlElement e,string s)
49 {
50
51 e.InvokeMember(s);
52 }
53
54 }
55 }
这是调用这个类的窗体代码:
01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Linq;
07 using System.Text;
08 using System.Windows.Forms;
09
10 namespace WebBrowser网页操作
11 {
12 public partial class Form1 : Form
13 {
14
15 Element el = new Element();
16
17 public Form1()
18 {
19 InitializeComponent();
20 }
21
22 private void Form1_Load(object sender, EventArgs e)
23 {
24 webBrowser1.Navigate(Application.StartupPath + @"\Test.html");
25 }
26
27 private void button1_Click(object sender, EventArgs e)
28 {
29 el.Write_value(el.GetElement_Name(webBrowser1,"username"),"isaced");
30 }
31
32 private void button2_Click(object sender, EventArgs e)
33 {
34 el.Write_value(el.GetElement_Id(webBrowser1, "password"), "123456");
35 }
36
37 private void button3_Click(object sender, EventArgs e)
38 {
39 el.Btn_click(el.GetElement_Id(webBrowser1,"button"),"click");//方法用的按钮click
40 }
41
42 private void button4_Click(object sender, EventArgs e)
43 {
44 el.Btn_click(el.GetElement_Form(webBrowser1, "form1"), "submit");//先获取表单,再调用表单的submit方法
45 }
46 }
47 }
转载于:https://www.cnblogs.com/haoyun99/archive/2012/07/05/2577161.html