C# Winform WebBrowser控件中操作網頁元素大全

  • C# Winform WebBrowser控件中操作網頁元素大全


1、獲取非input控件的值:

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

2、獲取input控件的值:

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

3、給輸入框賦值:

webBrowser1.Document.GetElementById("控件ID").SetAttribute("value", "控件值");

4、CheckBox選中:

webBrowser1.Document.GetElementById("控件ID").SetAttribute("Checked", "true");

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

//根據Parent,FirstChild,Children[1]數組,多少層級的元素都能找到。
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控件延遲執行提交按鈕事件:

this.timer1.Enabled = true;
this.timer1.Interval = 1000 * 2;
private void timer1_Tick(object sender, EventArgs e)
{
    this.timer1.Enabled = false;
    ClickBtn.InvokeMember("Click");//執行按扭操作
}

10、屏蔽腳本錯誤:

將WebBrowser控件ScriptErrorsSuppressed設置爲True即可

11、自動點擊彈出提示框:

參考:http://www.cnblogs.com/qqflying/archive/2012/07/25/2608038.html

12、獲取網頁中的Iframe,並設置Iframe的src

HtmlDocument docFrame = webBrowser1.Document.Window.Frames["mainFrame"].Document;

12、獲取網頁中的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/");

13、網頁中存在Iframe的時候webBrowser1.Url和webBrowser1_DocumentCompleted中的e.Url不一樣,前者是主框架的Url,後者是當前活動框口的Url。

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

14、讓控件聚焦

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

發佈了187 篇原創文章 · 獲贊 261 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章