2013-02-19 101 views
4

我使用網絡瀏覽器控件,文檔加載了HTML頁面。我想以編程方式從文檔中刪除一個元素。如何從Web瀏覽器控件中以編程方式刪除HTML元素?

任何人都可以指導我如何通過ID或名稱屬性刪除任何元素?

+0

刪除或隱藏? – pleinolijf 2013-02-19 14:56:19

+0

只能刪除。我知道隱藏很容易。 – Thomas 2013-02-19 15:00:02

+0

http://stackoverflow.com/questions/5006825/converting-webbrowser-document-to-a-bitmap – Thomas 2013-03-01 19:27:45

回答

3

您可以使用Microsoft.mshtml庫來完成此操作。我使用dynamic數據類型的功能完成它:

private void Form1_Load(object sender, EventArgs e) 
{ 
    webBrowser1.Navigate("https://www.google.com/"); 
} 

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    if (e.Url.ToString() == "https://www.google.com/") 
    { 
     dynamic htmldoc = webBrowser1.Document.DomDocument as dynamic; 
     dynamic node = htmldoc.getElementById("lga") as dynamic; 
     node.parentNode.removeChild(node); 
    } 
} 
1

這是VB.Net版本。我試圖刪除MsHTML。但引用該庫有它自己的問題。下面不是直接的答案,但可以解決方法來停止使用內置頁框加載外部資源

For Each FrameElement As HtmlElement In WebBrowser1.Document.GetElementsByTagName("iframe") 
     Debug.Print(FrameElement.OuterHtml) 
     FrameElement.OuterHtml = Nothing 

    Next 
0

OuterHtml無法修改!

此代碼刪除從網頁的CSS鏈接:

Sub RemoveStylesheet() 
 
     Dim styles As HTMLStyleSheetsCollection = WB.Document.DomDocument.styleSheets 
 
1: 
 
     If styles.length > 0 Then 
 
      For Each stl As Object In WB.Document.DomDocument.styleSheets 
 
       '  stl.removeImport(0) 
 
       If stl Is Nothing Then Continue For 
 
       Dim st As IHTMLElement = stl.owningElement 
 
       ' st.href = "" 
 
       ' MsgBox(st.tagName) 
 
       st.parentElement.removeChild(st) 
 
      Next 
 
      GoTo 1 
 
     End If 
 

 
     
 
    End Sub

6
webbrowser.Document.GetElementById("element").OuterHtml = ""; 
+0

是的,這有效,比Hanlet的解決方案更簡單,而且具有無需使用'dynamic'的優點。 – JonP 2016-09-30 12:27:11

相關問題