Search code examples
htmlwindowsbatch-filecmd

Fetch HTML and save it to a file with Windows command line


I'm trying to save the html source of a fetched web page into a file and I want to do this using only the CMD prompt on Windows.

I could do this with wget, but that requires using the wget program.

Is there any easy way to do this?


Solution

  • You may use a Batch-JScript hybrid script to do that in a very easy way. The JScript support is installed with all Windows versions from XP on.

    @if (@CodeSection == @Batch) @then
    
    @echo off
    CScript //nologo //E:JScript "%~F0" "%~1" > "%~N1.html"
    goto :EOF
    
    @end
    
    var http = WScript.CreateObject('Msxml2.XMLHTTP.6.0');
    http.open("GET", WScript.Arguments.Item(0), false);
    http.send();
    
    if (http.status == 200) {
       WScript.StdOut.Write(http.responseText);
    } else {
       WScript.StdOut.WriteLine("Error: Status "+http.status+" returned on download.");
    }
    

    Save previous code in a .BAT file, for example: GetHtmlCode.bat, and execute it with the web address in the first parameter:

    GetHtmlCode.bat "https://stackoverflow.com/questions/24975698/get-code-html-to-a-file-whit-cmd"
    

    I borrowed previous code from the accepted answer of this question and just did a couple small changes.