萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

C# 自動化操作 IE 獲取網頁 HTML 文檔:SHDocVw + MSHTML 實戰

透過 COM 自動化現有 IE 進程,獲取已打開頁面的 DOM 內容,適用於爬蟲、測試、數據提取等場景。

環境準備

  1. Visual Studio 建立 Console App (.NET Framework / .NET Core 3.1+)。
  2. 右鍵專案 → Add COM Reference → 勾選:
    • Microsoft Internet Controls (SHDocVw.dll) — IE 窗口枚舉。
    • Microsoft HTML Object Library (MSHTML.dll) — 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 等)。
  • 需在 UI 執行緒 (STAThread) 執行,Console App 預設 MTA,加 [STAThread] 屬性於 Main。

現代替代方案

  • Selenium / Playwright / Puppeteer Sharp:驅動真實瀏覽器 (Headless Chrome/Firefox),支援現代 Web、JS 渲染、等待策略、截圖、PDF。
  • HttpClient + AngleSharp/HtmlAgilityPack:純 HTTP 靜態解析,速度快、資源少,但無法執行 JS。
  • WebView2 (Edge Chromium):嵌入式 Evergreen 瀏覽器,可在 WPF/WinForms/WinUI 3 中自動化。

IE 已於 2022/6/15 退役,新專案**強烈建議**遷移至上述現代方案。

copyright © 萬盛學電腦網 all rights reserved