自訂搜尋

2010/10/25

C# webBrowser自動移除網頁元素(Elements)


我在寫一個瀏覽器
因為我被一些該死的圖片或是javascript或是廣告或是跳出視窗...bluhbluh~
弄得好煩!

嚴格上來說可以算是Pro版的BlockAd...=口=||
所以現在來筆記一下怎麼自動移除網頁裡面的元素~

我是利用mshtml的IHTMLDOMNode來完成
根據MSDN先生的說法


IHTMLDOMNode Interface

Provides methods to access all of the nodes in the document object model (DOM), to iterate the nodes, to insert nodes, to remove nodes, and to get the attributes of a node.

1.首先加一個參考Microsoft.mshtml

2.
using Microsoft.mshtml;

3.
HTMLDocument doc1 = webBrowser1.Document.Body.Document.DomDocument as HTMLDocument;
 
//所有連結
foreach (IHTMLElement element in doc1.links)
{
   IHTMLDOMNode node = element as IHTMLDOMNode;
   node.removeNode(true);
}

或是

HTMLDocument doc1 = webBrowser1.Document.Body.Document.DomDocument as HTMLDocument;
 
//所有圖片
foreach (IHTMLElement element in doc1.images)
{
   IHTMLDOMNode node = element as IHTMLDOMNode;
   node.removeNode(true);
}

或是

public void RemoveByTag(string Tag)
{
   HTMLDocument doc1 = webBrowser1.Document.Body.Document.DomDocument as HTMLDocument;
 
   //指定的標籤
   foreach (IHTMLElement element in doc1.getElementsByTagName(Tag))
   {
      IHTMLDOMNode node = element as IHTMLDOMNode;
      node.removeNode(true);
   }
}

沒有留言:

張貼留言

讀取中…