如何从WebBrowser组件获取HTMLElement的所有属性

Dev*_*ela 5 c# attributes webbrowser-control

我使用以下方法遍历DOM:

webBrowser.Document.Body.Parent.Children
Run Code Online (Sandbox Code Playgroud)

我想获得特定的所有属性HTMLElement.但是,HTMLElement只是有一个getAttribute方法.我正在寻找更像的东西htmlelement.attributes[n].因为我事先不知道这些属性.

Erx*_*der 2

如果 wbMain 是您的 WebBrowser1 控件,请执行以下操作。

首先,您需要获取对元素的引用,假设您想访问<A>页面的第一个链接,如果需要,您可以循环遍历所有链接。

这是在 VB 中,但在 C# 中是同样的事情,只是语法不同。

Dim i As Integer
Dim aElement As HTMLAnchorElement = wbMain.Document.All.getElementByTagName("A")(0)

For i = 0 To aElement.attributes.length - 1
  MsgBox aElement.attributes.item(i).name & "=" & aElement.attributes.item(i).value
Next i
Run Code Online (Sandbox Code Playgroud)

这将循环遍历所有属性并将其以某种格式显示在 MSGBOX 中name=value

如果您想按名称(属性名称)检索它,只需调用 usingaElement.getAttribute("target")从链接中检索目标属性值。

如果您想确认您获得了正确的对象/元素,只需执行 aaElement.outerHTML即可仅获取该元素的完整 HTML 代码。

由于我使用的是 .NET 之前的版本,如果给您带来麻烦,请随意将声明从 HTMLAnchorElement 更改为 IHTMLAnchorElement,当然,如果您想遍历页面上的所有元素,则可以使用 IHTMLElement,然后您就可以了对于页面上的第一个元素,需要做的是 wbMain.Document.All(0) ,或者循环直到 .All.length - 1 遍历所有元素。请记住,如果您使用嵌套的 For 循环,请不要使用 i 两次,而使用 j 作为其中之一:)。

如果这能回答您的问题,或者我是否可以采取更多措施来帮助您解决问题,请告诉我。