经常使用属性和方法javascript
Navigate(string urlString):浏览urlString表示的网址 Navigate(System.Uri url):浏览url表示的网址 Navigate(string urlString, string targetFrameName, byte[] postData, string additionalHeaders): 浏览urlString表示的网址,并发送postData中的消息//(一般咱们登陆一个网站的时候就会把用户名和密码做为postData发送出去) GoBack():后退 GoForward():前进 Refresh():刷新 Stop():中止 GoHome():浏览主页 WebBrowser控件的经常使用属性: Document:获取当前正在浏览的文档 DocumentTitle:获取当前正在浏览的网页标题 StatusText:获取当前状态栏的文本 Url:获取当前正在浏览的网址的 UriReadyState:获取浏览的状态 WebBrowser控件的经常使用事件: DocumentTitleChanged, CanGoBackChanged, CanGoForwardChanged, DocumentTitleChanged, ProgressChanged, ProgressChangedDocumentCompleted 页面加载完成以后的事件复制代码
一、获取非input控件的值:html
webBrowser1.Document.All["控件ID"].InnerText; 或webBrowser1.Document.GetElementById("控件ID").InnerText; 或webBrowser1.Document.GetElementById("控件ID").GetAttribute("value"); webBrowser_GrabCoupon.Document.GetElementsByTagName("控件标签").GetElementsByName("控件的name属性")[0].GetAttribute("style"); //经过标签获取元素
2.获取input控件的值:java
webBrowser1.Document.All["控件ID"].GetAttribute("value"); 或webBrowser1.Document.GetElementById("控件ID").GetAttribute("value");
三、给输入框赋值:web
//输入框 user.InnerText = "myname"; password.InnerText = "123456"; webBrowser1.Document.GetElementById("password").SetAttribute("value", "Welcome123");
四、下拉、复选、多选:windows
//下拉框: secret.SetAttribute("value", "question1"); //复选框 rememberme.SetAttribute("Checked", "True"); //多选框 cookietime.SetAttribute("checked", "checked");
五、根据已知有ID的元素操做没有ID的元素:cookie
HtmlElement btnDelete = webBrowser1.Document.GetElementById(passengerId).Parent.Parent.Parent.Parent.FirstChild.FirstChild.Children[1].FirstChild.FirstChild;
六、获取Div或其余元素的样式:并发
webBrowser1.Document.GetElementById("addDiv").Style;
七、直接执行页面中的脚本函数,带动态参数或不带参数都行:框架
Object[] objArray = new Object[1]; objArray[0] = (Object)this.labFlightNumber.Text; webBrowser1.Document.InvokeScript("ticketbook", objArray); webBrowser1.Document.InvokeScript("return false");
八、自动点击、自动提交:函数
HtmlElement btnAdd = doc.GetElementById("addDiv").FirstChild;btnAdd.InvokeMember("Click");
九、自动赋值,而后点击提交按钮的时候若是出现脚本错误或一直加载的问题,通常都是点击事件执行过快,这时须要借助Timer控件或者Application.DoEvents()延迟执行提交按钮事件:post
this.timer1.Enabled = true; this.timer1.Interval = 1000 * 2; private void timer1_Tick(object sender, EventArgs e) { this.timer1.Enabled = false; ClickBtn.InvokeMember("Click");//执行按扭操做 }
private void DelayClick() { //下面的代码表示延迟1秒执行点击操做,且不会像Thread.Sleep(1000)那样会形成程序短暂假死,不过效率会有所下降 DateTime time = DateTime.Now; while (time.AddSeconds(1) >= DateTime.Now) { Application.DoEvents(); } ClickBtn.InvokeMember("Click");//执行按扭操做 }
补充:C#中Application.DoEvents()的做用
Visual Studio里的摘要:处理当前在消息队列中的全部 Windows 消息。
交出CPU控制权,让系统能够处理队列中的全部Windows消息,好比在大运算量循环内,加Application.DoEvents能够防止界面中止响应,由于winform的消息循环是一个线程来处理,那么假如你的某个操做比较耗时,那么消息处理得等你这个耗时操做作完了才能继续,而Application.DoEvents方法就是容许你在耗时操做的内部调用它,而去处理消息队列中的消息。像鼠标移动鼠标点击都是windows消息,若是耗时操做一直进行,那么界面就像死锁同样。值得注意的是,使用Application.DoEvents的同时也会下降程序性能
(Application.DoEvents在处理耗时操做中使用得比较多)
十、屏蔽脚本错误:
将WebBrowser控件ScriptErrorsSuppressed设置为True便可
十一、自动点击弹出提示框:使用IHTMLDocument2须要加入对Microsoft HTML Object Library的引用:
(若是没有Microsoft HTML Object Library则先要添加COM组件,浏览文件引入Microsoft.mshtml.dll,文件地址是C:\WINDOWS\system32\mshtml.dll)
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { //自动点击弹出确认或弹出提示 IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument; vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript"); //弹出确认 vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript");//弹出提示 }
12.WebBrowser页面加载完毕以后,在页面中进行一些自动化操做的时候弹出框的自动点击(屏蔽):
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { //自动点击弹出确认或弹出提示 IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument; vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript"); //弹出确认 vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript");//弹出提示 //下面是你的执行操做代码 }
1三、获取网页中的Iframe,并设置Iframe的src:
HtmlDocument docFrame = webBrowser1.Document.Window.Frames["mainFrame"].Document; 或 HtmlDocument docFrame = webBrowser1.Document.All.Frames["mainFrame"].Document; docFrame.All["mainFrame"].SetAttribute("src", "http://www.baidu.com/");
网页中存在Iframe的时候webBrowser1.Url和webBrowser1_DocumentCompleted中的e.Url不同,前者是主框架的Url,后者是当前活动框口的Url。
1四、让控件聚焦:
this.webBrowser1.Select(); this.webBrowser1.Focus(); doc.All["TPL_password_1"].Focus();
1五、打开本地网页文件:
webBrowser1.Navigate(Application.StartupPath + @"\Test.html");
1六、获取元素、表单:
//根据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); }
1七、获取Cookie:
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern bool InternetGetCookieEx(string pchUrl, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);
private static string GetCookieString(string url) { uint datasize = 1024; StringBuilder cookieData = new StringBuilder((int)datasize); if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero)) { if (datasize < 0) return null; cookieData = new StringBuilder((int)datasize); if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero)) return null; } return cookieData.ToString(); }
private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e) { richTextBox1.Text = string.Empty; if (cbcookie.Checked) { if (checkBox1.Checked) { richTextBox1.Text = GetCookieString(textBox1.Text.Trim()); } else { richTextBox1.Text = webBrowser1.Document.Cookie; } } }
1八、设置代理:
1.首先建一个代理信息的结构体
/// <summary> /// 代理结构体 /// </summary> public struct Struct_INTERNET_PROXY_INFO { public int dwAccessType; public IntPtr proxy;//IP以及端口号 public IntPtr proxyBypass; }
2.设置代理的具体实现
/// <summary> /// 设置代理的Api /// </summary> /// <returns></returns>
[DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);
/// <summary> /// 代理IP以及端口号 /// </summary> /// <param name="strProxy"></param> private void RefreshIESettings(string strProxy) { const int INTERNET_OPTION_PROXY = 38; const int INTERNET_OPEN_TYPE_PROXY = 3; Struct_INTERNET_PROXY_INFO struct_IPI; // Filling in structure struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY; struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy); struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local"); // Allocating memory IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI)); // Converting structure to IntPtr Marshal.StructureToPtr(struct_IPI, intptrStruct, true); bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI)); }
3.使用的时候直接调用就能够了
RefreshIESettings("41.129.53.227:80"); webBrowser1.Navigate("http://www.baidu.com");
1九、怎么在加载完成某个页面以后执行代码:
//本事件是当每次加载完成当前页面后才会执行的 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { //e.Url是当前加载的页面, if (e.Url.ToString().Contains("http://www.google.com")) { //执行操做1 } else if (e.Url.ToString().Contains("http://www.baidu.com")) { //执行操做2 } }
20、怎么禁止在新窗口中打开网页:
private void webBrowser1_NewWindow(object sender, CancelEventArgs e) { string url = ((System.Windows.Forms.WebBrowser)sender).StatusText; webBrowser1.Navigate(url); e.Cancel = true; }
2一、怎么设置Cookie:
webBrowser1.Document.Cookie=“你的Cookie值”;