3
\$\begingroup\$

I've written a script in VBA which is able to scrape images from a webpage and save it to a customized folder successfully. Firstly, it scrapes the image link then downloads the image and rename it according to it's identity. It takes 2/3 seconds to accomplish the task. I tried to do the whole thing specklessly. Here is the script I tried with:

Sub SavingImages()
Dim http As New XMLHTTP60, htmldoc As New HTMLDocument
Dim htmlas As Object, htmla As Object, html As Object
Dim stream As Object, tempArr As Variant
Dim fileSource As String
With http
 .Open "GET", "https://www.yify-torrent.org/search/1080p/", False
 .send
 htmldoc.body.innerHTML = .responseText
End With
Set htmlas = htmldoc.getElementsByClassName("movie")
For Each htmla In htmlas
 Set html = htmla.getElementsByTagName("img")(0)
 fileSource = Replace(html.src, "about", "http")
 tempArr = Split(html.src, "/")
 tempArr = tempArr(UBound(tempArr))
 With http
 .Open "GET", fileSource, False
 .send
 End With
 Set stream = CreateObject("ADODB.Stream")
 stream.Open
 stream.Type = 1
 stream.write http.responseBody
 stream.SaveToFile ("D:\Test\Images\" & tempArr & ".jpg")
 stream.Close
Next htmla
End Sub
asked Jul 7, 2017 at 17:23
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The code is quite clear to read and understand. There are only minor things I would improve:

  • better variable names - tempArr, for example, is a bad name - what about:

    fileSource = Replace(html.src, "about", "http")
    urlParts = Split(html.src, "/")
    imageFileName = urlParts(UBound(urlParts))
    

    and then use imageFileName instead of tempArr later on. Also think of better names for htmla and htmlas.

  • you can use with for the stream variable as well

  • avoid "hardcoding" - define "D:\Test\Images\" path as a constant, or as a parameter for your function
  • you can also iterate over the img elements directly if you do:

    Set movieImages = htmldoc.querySelectorAll(".movie img")
    
answered Jul 7, 2017 at 18:10
\$\endgroup\$
1
  • \$\begingroup\$ Thanks sir alecxe, for your suggestion to do the betterment of my script. It feels good to get the accreditation of my script from a giant coder like you. Thanks again. \$\endgroup\$ Commented Jul 7, 2017 at 18:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.