1. 程式人生 > >C#WebBrowser控件使用教程與技巧收集

C#WebBrowser控件使用教程與技巧收集

運算 gre OS 延遲執行 progress pch parent event ieda

常用屬性和方法

技術分享圖片
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 頁面加載完成之後的事件復制代碼
技術分享圖片

1、獲取非input控件的值:

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控件的值:

webBrowser1.Document.All["控件ID"].GetAttribute("value");
或webBrowser1.Document.GetElementById("控件ID").GetAttribute("value");

3、給輸入框賦值:

//輸入框
user.InnerText = "myname";
password.InnerText = "123456";
webBrowser1.Document.GetElementById("password").SetAttribute("value", "Welcome123");

4、下拉、復選、多選:

技術分享圖片
//下拉框:
secret.SetAttribute("value", "question1"); 
//復選框
rememberme.SetAttribute("Checked", "True");
//多選框
cookietime.SetAttribute("checked", "checked");
技術分享圖片

5、根據已知有ID的元素操作沒有ID的元素:

HtmlElement btnDelete = webBrowser1.Document.GetElementById(passengerId).Parent.Parent.Parent.Parent.FirstChild.FirstChild.Children[1].FirstChild.FirstChild;

6、獲取Div或其他元素的樣式:

webBrowser1.Document.GetElementById("addDiv").Style;

7、直接執行頁面中的腳本函數,帶動態參數或不帶參數都行

Object[] objArray = new Object[1];
objArray[0] = (Object)this.labFlightNumber.Text;
webBrowser1.Document.InvokeScript("ticketbook", objArray);
webBrowser1.Document.InvokeScript("return false");

8、自動點擊、自動提交:

HtmlElement btnAdd = doc.GetElementById("addDiv").FirstChild;btnAdd.InvokeMember("Click");

9、自動賦值,然後點擊提交按鈕的時候如果出現腳本錯誤或一直加載的問題,一般都是點擊事件執行過快,這時需要借助Timer控件或者Application.DoEvents()延遲執行提交按鈕事件:

技術分享圖片
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在處理耗時操作中使用得比較多)

10、屏蔽腳本錯誤:

將WebBrowser控件ScriptErrorsSuppressed設置為True即可

11、自動點擊彈出提示框:使用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");//彈出提示
    //下面是你的執行操作代碼
}
技術分享圖片

13、獲取網頁中的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。

14、讓控件聚焦:

this.webBrowser1.Select();
this.webBrowser1.Focus();
doc.All["TPL_password_1"].Focus();

15、打開本地網頁文件:

webBrowser1.Navigate(Application.StartupPath + @"\Test.html");

16、獲取元素、表單:

技術分享圖片
//根據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);
}
技術分享圖片

17、獲取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; } } }
技術分享圖片

18、設置代理:

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");

19、怎麽在加載完成某個頁面之後執行代碼:

技術分享圖片
//本事件是當每次加載完成當前頁面後才會執行的
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;
}
技術分享圖片

21、怎麽設置Cookie:

webBrowser1.Document.Cookie=“你的Cookie值”;

C#WebBrowser控件使用教程與技巧收集