c# WebBrowser网页操作-元素获取_事件操作

时间:2021-08-03 08:45:17
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方法 } } }