【C#】通過遍歷IFrame訪問頁面元素
阿新 • • 發佈:2019-01-06
最近在做一個小專案,期間需要用到C#去操作IE頁面中的元素,實現自動填寫表單並且提交的功能,想這網上關於這方面的東西肯定很多,於是開始在網上找資料。
1.首先新增必須的兩個控制元件的引用
Microsoft Internet Controls
Microsoft HTML Object Library
2.遍歷所有的IE視窗
3.通過DOM操作IE頁面SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass(); foreach (InternetExplorer Browser in shellWindows) { if (Browser.Document is HTMLDocument && Browser.LocationURL.Contains("ra207.com")) { mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)Browser.Document; //... } }
mshtml.IHTMLElementCollection inputs = (mshtml.IHTMLElementCollection)doc2.all.tags("INPUT"); mshtml.HTMLInputElement input1 = (mshtml.HTMLInputElement)inputs.item("kw1", 0); input1.value = "test"; mshtml.IHTMLElement element2 = (mshtml.IHTMLElement)inputs.item("su1", 0); element2.click();
4.遍歷操作IFrame中的元素
很不巧的是原作者也沒有實現直接對IFrame中元素的操作,在網上找了很久也沒有找到相關的文章,沒有辦法,只能自己搞了。
分析網頁結構,是多層IFrame相互巢狀的複雜結構,並且上層是無法獲取子層的元素的,真是麻煩~
後來轉念一想,既然是多層巢狀,那不正好可以用遞迴來實現麼,遍歷所有的IFrame應該可行,暴力美學~
//遍歷IFrame public static bool FramesRecursion(ref IHTMLWindow2 frame) { IHTMLDocument2 frameDoc = frame.document; if (null == frameDoc) return false; if (null == frameDoc.body.innerHTML) return false; if (frameDoc.body.innerHTML.Contains("確定交易")) //找到目標 { FindAndClickTheButton(ref frame); //操作目標 return true; } //遍歷該IFrame包含的所有子IFrame IHTMLFramesCollection2 frames = (IHTMLFramesCollection2)frameDoc.frames; int len = frames.length; if (len <= 0) return false; object i = 0; object olen = len; while ((int)i < (int)olen) { IHTMLWindow2 frame2 = frames.item(ref i) as IHTMLWindow2; if (FramesRecursion(ref frame2)) return true; i = (object)((int)i + 1); } return false; }
最後打包程式的時候需要這兩個庫對應的Dll放在exe同一個目錄下面,否則很可能因為dll版本的不同造成不報錯的失敗。