usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms;// namespaceWebBrowser網頁操作 { publicclassElement { //根據Name獲取元素 publicHtmlElement GetElement_Name(WebBrowser wb,stringName) { HtmlElement e = wb.Document.All[Name]; returne; } //根據Id獲取元素 publicHtmlElement GetElement_Id(WebBrowser wb, stringid) { HtmlElement e = wb.Document.GetElementById(id); returne; } //根據Index獲取元素 publicHtmlElement GetElement_Index(WebBrowser wb,intindex) { HtmlElement e = wb.Document.All[index]; returne; } //獲取form表單名name,返回表單 publicHtmlElement GetElement_Form(WebBrowser wb,stringform_name) { HtmlElement e = wb.Document.Forms[form_name]; returne; } //設置元素value屬性的值 publicvoidWrite_value(HtmlElement e,stringvalue) { e.SetAttribute("value", value); } //執行元素的方法,如:click,submit(需Form表單名)等 publicvoidBtn_click(HtmlElement e,strings) { e.InvokeMember(s); } } } 這是調用這個類的窗體代碼: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; namespaceWebBrowser網頁操作 { publicpartialclassForm1 : Form { Element el = newElement(); publicForm1() { InitializeComponent(); } privatevoidForm1_Load(objectsender, EventArgs e) { webBrowser1.Navigate(Application.StartupPath + @"\Test.html"); } privatevoidbutton1_Click(objectsender, EventArgs e) { el.Write_value(el.GetElement_Name(webBrowser1,"username"),"isaced"); } privatevoidbutton2_Click(objectsender, EventArgs e) { el.Write_value(el.GetElement_Id(webBrowser1, "password"), "123456"); } privatevoidbutton3_Click(objectsender, EventArgs e) { el.Btn_click(el.GetElement_Id(webBrowser1,"button"),"click");//方法用的按鈕click } privatevoidbutton4_Click(objectsender, EventArgs e) { el.Btn_click(el.GetElement_Form(webBrowser1, "form1"), "submit");//先獲取表單,再調用表單的submit方法 } } }