Hack 82 Program XML/HTTP with VBScript


Accessing Amazon within Windows is a job for VBScript.

VBScript is a common scripting language for the Windows platform. It's very similar to Visual Basic, and in fact this hack is modified from the example VBA application included with the Amazon developer's kit. With a few slight modifications, this code could be used in a Word macro, a Visual Basic program, or an ASP web page. In this case, it's written for Windows Scripting Host, and will run just like any other program.

82.1 What You Need

This example requires a Windows machine and the Microsoft XML Parser. If Internet Explorer 4.0 or higher is installed on your machine, the parser is already there.

82.2 The Code

Create a text file called amazon_price.vbs with the following code:

' amazon_price.vbs
' This VBScript prompts for an ASIN, and returns the price.
' Usage: double-click amazon_price.vbs, enter ASIN.

Sub AmazonQuery(ASIN_In)
  Dim SelectedText
  Dim Loaded
  ' Make sure that some text is selected
  If ((Len(ASIN_In) = 0) Or (ASIN_In < " ")) Then
    WScript.Echo "Please enter an ASIN."
    Exit Sub
  End If
  ' Set Associate ID and Developer Token
  AffiliateTag = "insert associate tag"
  DeveloperToken = "insert developer token"
  ' Create an instance of the MSXML Parser
  Set MSXML = CreateObject("MSXML.DOMDocument")
  ' Set MSXML Options
  MSXML.Async = False
  MSXML.preserveWhiteSpace = False
  MSXML.validateOnParse = True
  MSXML.resolveExternals = False
  ' Form the request URL
  XMLURL = "http://xml.amazon.com/onca/xml3" + _
           "?t=" + AffiliateTag + _
           "&dev-t=" + DeveloperToken + _
           "&page=1" + _
           "&f=xml" + _
           "&mode=books" + _
           "&type=lite" + _
           "&AsinSearch=" + ASIN_In
  ' Issue the request and wait for the response
  Loaded = MSXML.Load(XMLURL)

  ' If the request is loaded successfully, continue
  If (Loaded) Then

    ' Look for the ErrorMsg tag
    Set XMLError = MSXML.SelectNodes("//ErrorMsg")
    ' If it exists, display the message and exit
    If XMLError.length > 0 Then
       WScript.Echo MSXML.SelectSingleNode("//ErrorMsg").text
       Exit Sub
    End If

    ' If there's no error, use XPath to get the product name
    ' and the price
    WScript.Echo "The price of " + _
      MSXML.SelectSingleNode("ProductInfo/Details/ProductName").text + _
      " is " + _
    WScript.Echo "The service is not available."
  End If
End Sub

strASIN = InputBox("Please enter a product ASIN.")


As you can see, this script looks for two specific pieces of information in the response: the product name and the price. The XPath queries to reach those pieces of info are:


By changing these paths, you can bring up any other bits of available data.

82.3 Running the Hack

To run this code, double-click the file you created. You should be prompted for an ASIN. The script will contact Amazon and return the price.