C#】通過遍歷IFrame訪問頁面元素


最近在做一個小項目,期間需要用到C#去操作IE頁面中的元素,實現自動填寫表單並且提交的功能,想這網上關於這方面的東西肯定很多,於是開始在網上找資料。

在逆心的博客上找到些東西對自己幫助很大,原文鏈接:http://www.cnblogs.com/kissdodog/p/3725774.html

 

1.首先添加必須的兩個控件的引用

Microsoft Internet Controls
Microsoft HTML Object Library

 

2.遍歷所有的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;
//...
}
}


3.通過DOM操作IE頁面
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版本的不同造成不報錯的失敗。
---------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM