透過 COM 自動化現有 IE 進程,獲取已打開頁面的 DOM 內容,適用於爬蟲、測試、數據提取等場景。
using System;
using System.IO;
using SHDocVw;
using mshtml;
class Program {
static void Main() {
ShellWindows shellWindows = new ShellWindowsClass();
foreach (InternetExplorer ie in shellWindows) {
string filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename == "iexplore") {
Console.WriteLine("Web Site: " + ie.LocationURL);
IHTMLDocument2 htmlDoc = ie.Document as IHTMLDocument2;
if (htmlDoc != null && htmlDoc.body != null) {
string snippet = htmlDoc.body.outerHTML.Substring(0, Math.Min(40, htmlDoc.body.outerHTML.Length));
Console.WriteLine("Document Snippet: " + snippet);
} else {
Console.WriteLine("Document Snippet: ***Failed***");
}
Console.WriteLine();
}
}
Console.ReadKey();
}
}
ShellWindows 枚舉所有 Shell 窗口(含資源管理器、IE),用進程名 iexplore 過濾。ie.Document 返回 IHTMLDocument2,提供完整 DOM API (getElementById, querySelectorAll, outerHTML 等)。[STAThread] 屬性於 Main。IE 已於 2022/6/15 退役,新專案**強烈建議**遷移至上述現代方案。