0

I found an Excel/VBA script here and am trying to translate it to Python. First is the VBA, then my Python attempt. How should I fix the Python code?

Public Function GetUPSDeliveryDate(ByVal id As String) As String
Dim body As String, json As Object
body = "{""Locale"":""en_US"",""TrackingNumber"":[""" & id & """]}"
With CreateObject("MSXML2.XMLHTTP")
    .Open "POST", "https://www.ups.com/track/api/Track/GetStatus?loc=en_US", False
    .setRequestHeader "Referer", "https://www.ups.com/track?loc=en_US&requester=ST/"
    .setRequestHeader "User-Agent", "Mozilla/5.0"
    .setRequestHeader "DNT", "1"
    .setRequestHeader "Content-Type", "application/json"
    .setRequestHeader "Accept", "application/json, text/plain, */*"
    .send body
    Set json = JsonConverter.ParseJson(.responseText)
End With

Excel VBA/JSON to scrape UPS tracking delivery

My attempt is:

def f(tn):
  data = {"Locale":"en_US",
    "TrackingNumber":f"[{tn}]",
    "Referer": "https://www.ups.com/track?loc=en_US&requester=ST/",
    "User-Agent": "Mozilla/5.0",
    "DNT": "1",
    "Content-Type": "application/json",
    "Accept": "application/json, text/plain, */*"}

  r = requests.post("https://www.ups.com/track/api/Track/GetStatus?loc=en_US", data=data)
  print(r.json())

My guess is one problem is putting the body portion from VBA into data.

1
  • As @Tim Roberts' answer says, right now you are including all the headers in the POST data. They should be passed in separately as headers. Commented Mar 14, 2021 at 1:56

1 Answer 1

2

Right. Locale and TrackingNumber are part of the data. Everything else is a request header.

def f(tn):
  data = {"Locale":"en_US",
    "TrackingNumber":f"[{tn}]"}
  headers = {
    "Referer": "https://www.ups.com/track?loc=en_US&requester=ST/",
    "User-Agent": "Mozilla/5.0",
    "DNT": "1",
    "Content-Type": "application/json",
    "Accept": "application/json, text/plain, */*"}

  r = requests.post("https://www.ups.com/track/api/Track/GetStatus?loc=en_US", data=data, headers=headers)
  print(r.json())
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Alas, I'm getting an Access Denied error, but that would seem a problem with the original code (which I have not tested).

Your Answer

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.