Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ALL attributes of an HTMLElement from WebBrowser Component

I am traversing the DOM using:

webBrowser.Document.Body.Parent.Children

I want to get all attributes of a specific HTMLElement. However, the HTMLElement just have a getAttribute method. I am looking for something more like htmlelement.attributes[n]. Because I dont know the attributes beforehand.

like image 365
Devela Avatar asked Oct 08 '22 17:10

Devela


2 Answers

If wbMain is your WebBrowser1 control, do the following.

First, you need to get a ref to your element, lets say you want to access the first <A> link, of your page, you can loop through all if you want.

This is in VB, but its the same sort of thing in C#, just different syntax.

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

This will loop through all attributes and display it in a MSGBOX in a name=value format.

If you want to retreive it by name (attributes name) just call using aElement.getAttribute("target") to retreive the target attributes value from the a Link.

If you want to confirm you got the right object/element, just do a aElement.outerHTML to get the full HTML code for that element only.

Since I am using a pre.NET version, feel free to change the declaration from HTMLAnchorElement to IHTMLAnchorElement if it gives you trouble, of course, you can just use IHTMLElement if you want to go through all elements on a page, then all you'll need to do is wbMain.Document.All(0) for first element on a page, or loop until .All.length - 1 to go through all. Remember if you are using nested For loops, don't use i twice, use j for one of them :).

Let me know if this answers your question or if there is more I can do to help you with your issue.

like image 190
Erx_VB.NExT.Coder Avatar answered Oct 13 '22 12:10

Erx_VB.NExT.Coder


you can use HtmlAgilityPack to parse html doc in u r case u can use

var doc = new HtmlAgilityPack.HtmlDocument();
   doc.Load(FileName);
   var node = doc.DocumentNode.SelectNodes("//NameofHtmlTag")[0];
   foreach (HtmlAgilityPack.HtmlAttribute attri in node.Attributes)
    {
       //iterate through attributes
    }    
like image 34
Smack Avatar answered Oct 13 '22 11:10

Smack