Using getElementsBy??Name in Excel VBA

Viewed 655

I'm attempting to use VBA to scrape the link to a .gif file from this HTML fragment:

        <div class="row">
            <div class="col-md-12">
                <div id='imageDiv' style='width:99%'>
 <img style='width:99% !important; border:5px solid silver;' src="http://www.[rest of link].gif" alt="" />
  </div>

My code below :

parent_url = "http://www.[webpage url]" 
objIE.navigate parent_url
        While objIE.Busy Or objIE.readyState <> 4
            DoEvents
        Wend
        For Each ele In objIE.document.getElementsByTagName("imageDiv")
           If InStr(ele.Style, "width") > 0 Then
              ws1.Cells(2, 2) = ele.innerText: Exit For
           End If
        Next
objIE.Quit

This doesn't write anything to the spreadsheet even when I try a number of different element types. Any pointers about what I'm doing wrong here? TIA

3 Answers

Try:

For Each ele In objIE.document.getElementById("imageDiv").getElementsByTagName("img")

Firstly, as pointed out by Tim Williams, imageDiv is an id and not a tag, so it can be reached via .getElementById() method, which returns a unique HTML element, in contrast to .getElementsByTagName() which returns a collection of HTML elements.

A tag in HTML, in its simplest form looks like <TagName>Inner Text</>.

So in your case, the tag name you are looking for is img and the id you're looking for is imageDiv.

So, if you want to get the element whose id is imageDiv and then get its img elements, and more specifically its first img element you would have to do it like so:

Dim img As HTMLImg
Set img = objIE.document.getElementById("imageDiv").getElementsByTagName("img")(0)

Secondly, the innerText is not what you are looking for. What you need is the src.

This can be reached like so:

Debug.Print img.src

To take advantage of the .src property, we store the element in a HTMLImg variable.

The code above will print the following to your immediate window:

http://www.[rest%20of%20link].gif/

References Used: Microsoft HTML Object Library

In addition to the answers given it is more efficient and faster to use a css selector which returns a single node

Debug.Print objIE.document.querySelector("#imageDiv img").src
Related