【C#】[网络]WebBrowser网页操作(提取元素,自动填表)
说明:做了个简单的表单html文件,方便查看效果。附件中:bin\Debug\Test.html
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms;// namespace WebBrowser网页操作 { public class Element { //根据Name获取元素 public HtmlElement GetElement_Name(WebBrowser wb,string Name) { HtmlElement e = wb.Document.All[Name]; return e; } //根据Id获取元素 public HtmlElement GetElement_Id(WebBrowser wb, string id) { HtmlElement e = wb.Document.GetElementById(id); return e; } //根据Index获取元素 public HtmlElement GetElement_Index(WebBrowser wb,int index) { HtmlElement e = wb.Document.All[index]; return e; } //获取form表单名name,返回表单 public HtmlElement GetElement_Form(WebBrowser wb,string form_name) { HtmlElement e = wb.Document.Forms[form_name]; return e; } //设置元素value属性的值 public void Write_value(HtmlElement e,string value) { e.SetAttribute("value", value); } //执行元素的方法,如:click,submit(需Form表单名)等 public void Btn_click(HtmlElement e,string s) { e.InvokeMember(s); } } }
这是调用这个类的窗体代码:
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; namespace WebBrowser网页操作 { public partial class Form1 : Form { Element el = new Element(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { webBrowser1.Navigate(Application.StartupPath + @"\Test.html"); } private void button1_Click(object sender, EventArgs e) { el.Write_value(el.GetElement_Name(webBrowser1,"username"),"isaced"); } private void button2_Click(object sender, EventArgs e) { el.Write_value(el.GetElement_Id(webBrowser1, "password"), "123456"); } private void button3_Click(object sender, EventArgs e) { el.Btn_click(el.GetElement_Id(webBrowser1,"button"),"click");//方法用的按钮click } private void button4_Click(object sender, EventArgs e) { el.Btn_click(el.GetElement_Form(webBrowser1, "form1"), "submit");//先获取表单,再调用表单的submit方法 } } }