Sunday, February 13, 2011

Vbscript: Downloading a Webpage to File

Took me an hour to find the cause of my pains. Thanks to Jon Bohagier @ bohack.com [article].

Error when saving a website: "Microsoft VBScript runtime error: Invalid procedure call or argument"
Issue = Unicode is evil
Solution = Convert to ascii



Dim FSO, dFile, sHTML

sHTML = Get_HTML ("http://www.google.com")

Set FSO = CreateObject("Scripting.FileSystemObject")
Set dFile = FSO.CreateTextFile("SaveFile.html", True)

dFile.Write UniToAsc(sHTML)
dFile.Close

Set dFile = Nothing
Set FSO = Nothing

Private Function Get_HTML (up_http)
 Dim xmlhttp
 Set xmlhttp = createobject("msxml2.xmlhttp.6.0")

 xmlhttp.open "get", up_http, False
 xmlhttp.send
 Get_HTML = xmlhttp.responsetext

 set xmlhttp = Nothing
End Function

Private Function UniToAsc(sString)
 Dim nLen, nPTR, sAsc
 nLen = Len(sString)

 For nPTR = 1 To nLen
  sAsc = sAsc & Chr(Asc(Mid(sString, nPTR, 1)))
 Next

 UniToAsc = sAsc
End Function

No comments: