我使用 Web 浏览器控件,并且文档加载了 HTML 页面。我想以编程方式从文档中删除一个元素。
谁能指导我如何通过 ID 或名称属性删除任何元素?
webbrowser.Document.GetElementById("element").OuterHtml = "";
您可以使用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);
}
}
它是 VB.Net 版本。我尝试删除MsHTML
. 但是引用该库有其自身的问题。以下不是直接答案,但可以解决使用iframes
.
For Each FrameElement As HtmlElement In WebBrowser1.Document.GetElementsByTagName("iframe")
Debug.Print(FrameElement.OuterHtml)
FrameElement.OuterHtml = Nothing
Next
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