Get src attribute from img tag in web page with vba

How to parse or get the src attribute from the img tag in a web page automatically with VBA. Let’s have a look at the complete HTML code structureof the img tag:

HTML <img> Tag
We can insert an image in a web page using the following code:
<img src=”smiley.gif” alt=”Smiley face” height=”42″ width=”42″>

The <img> tag defines an image in an HTML page.
The <img> tag has two required attributes: src and alt.
HTML <img> src Attribute
<img src=”URL”>
URL represents the URL of the image.
Possible values:
An absolute URL – it points to another web site (like src=””)
A relative URL – it points to a file within the same folder (like src=”image.jpg”)

When a web page loads in a web browser like the Internet Explorer or Google Chrome, it gets the image from a web server and inserts it into the page. Therefore, we make sure that the image is actually located  in the same folder in relation to the web page or in the specified URL or web address; otherwise our visitors will get a broken link icon. The broken link icon is shown if the browser cannot find the image and the alt attribute can help us get an idea of the image.

Watch the video below to learn how we automate the process of extracting all the links connected to the src values in columns wit VBA:

Watch this video on YouTube.

Here’s the complete VBA code:

Sub getSrcAttributeImgTag()
Dim ie As InternetExplorer
Dim html As HTMLDocument
Dim ElementCol As Object, Link As Object
Dim ecol As Long

Application.ScreenUpdating = False

Set ie = New InternetExplorer
ie.Visible = False

ie.navigate “”

Do While ie.readyState <> READYSTATE_COMPLETE
Application.StatusBar = “Trying to go to website…”

Set html = ie.document

Range(“A1”) = “extracted links”
Set ElementCol = html.getElementsByTagName(“img”)

For Each Link In ElementCol
ecol = Worksheets(“sheet1”).Cells(1, Columns.Count).End(xlToLeft).Offset(0, 1).Column
Cells(1, ecol).Value = Link.src
Cells(1, ecol).Columns.AutoFit

Set ie = Nothing
Application.StatusBar = “”
Application.ScreenUpdating = True

End Sub

Further reading:

Automate Scraping of Hyperlinks from Web Pages Using Excel VBA

Find last row column cell in an Excel worksheet with VBA