用C#從IE瀏覽器中擷取HTML文檔

來源:互聯網
上載者:User

用C#從IE中擷取HTML文檔

You need to extract the html from the current web page in IE. This article details how to do that.

這篇文章描述如何獲得IE瀏覽器當前網頁的HTML文檔。

  1. Create a console application in any version of Visual Studio using .Net version 1|2|3|3.5.
  2. Add two Com object references which will allow us to manipulate IE.

 

  1. 用 Visual Studio 的任意版本建立一個控制台程式。
  2. 添加2個COM對象引用用來操作IE

  3. Note the code sample below does not require the using directive for the objects, so just add the code as is.
  4. Then find the instances of IE and extract the document:
  5. 添加下面代碼
  6. 開啟IE擷取HTML文檔
SHDocVw.ShellWindows shellWindows
= new SHDocVw.ShellWindowsClass();
 
string filename;
 
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename
= Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
 
if (filename.Equals("iexplore"))
{
Console.WriteLine("Web Site   : {0}", ie.LocationURL);
 
mshtml.IHTMLDocument2 htmlDoc
= ie.Document as mshtml.IHTMLDocument2;
 
Console.WriteLine("   Document Snippet: {0}",
( ( htmlDoc != null ) ? htmlDoc.body.outerHTML.Substring(0, 40)
: "***Failed***" ));
Console.WriteLine("{0}{0}", Environment.NewLine);
}
}

Here is a screen-shot of the output:

程式:

 

代碼:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
         {
            SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
            string filename;
            foreach (SHDocVw.InternetExplorer ie in shellWindows)
             {
                filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
                if (filename.Equals("iexplore"))
                 {
                    Console.WriteLine("Web Site    : {0}", ie.LocationURL);
                    mshtml.IHTMLDocument2 htmlDoc = ie.Document as mshtml.IHTMLDocument2;
                    Console.WriteLine("    檔案 Snippet: {0}", ((htmlDoc != null) ? htmlDoc.body.outerHTML.Substring(0, 40) : "***Failed***"));
                    Console.WriteLine("{0}{0}", Environment.NewLine);
                 }
             }
         }
     }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.