javascript - 使用 VBA 的 XHR 请求和 JSON 响应

标签 javascript json vba excel

我正在尝试从电子商务时尚网站获取一些数据。当我在网站上打开一个类别时,我可以看到 48 个项目,最后还有一个加载更多按钮。当我单击该按钮时,我会看到接下来的 48 项。反手发生的情况是,当我单击加载更多按钮时,会发送 XHR post 请求并以 JSON 格式返回响应。我想自动执行此搜索并在 Excel 工作表中捕获响应数据。我是编程新手,不熟悉高级脚本语言,所以我正在研究 VBA。我的请求已提交但未得到回复。我的类别页面是http://www.myntra.com/_发送请求的链接是 http://www.myntra.com/searchws/search/styleids2 。 这是我的代码:

    Sub post()
    Dim objHTTP As Object
    Dim result As String
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.navigate "about:blank"
    objIE.Visible = True
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://www.myntra.com/searchws/search/styleids2"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
   objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
   objHTTP.send ("query=(full_text_myntra:(_)AND(statusid:1008))&start=0&rows=500&facet=true&facetField=[]")
   result = objHTTP.responsetext
   objIE.document.Write result

   Set objHTTP = Nothing
  End Sub     

最佳答案

尝试使用 Postman 运行查询时,我遇到了很多 415 错误。看起来 API 需要 JSON 而不是表单 urlencoded,并且参数需要包装在数组中,所以我会在您的代码中检查这一点:

"[{""query"":""(full_text_myntra:(_)AND(statusid:1008))"",""start"":0,""rows"":500,""facet"":true,""facetField"":[]}]"

此外,我建议使用类似 Excel-REST 的内容(这是我为遇到的类似情况所做的)以帮助创建请求和处理 JSON:

Dim MyntraClient As New RestClient
MyntraClient.BaseUrl = "http://www.myntra.com/"

' With inline JSON
Dim json As String
json = "[{""query"":""(full_text_myntra:(_)AND(statusid:1008))"",""start"":0,""rows"":500,""facet"":true,""facetField"":[]}]"

Dim Response As RestResponse
Set Response = MyntraClient.PostJSON("searchws/search/styleids2", json)

' It's no fun creating json string by hand, instead create it via Dictionary/Collection/Array
Dim SearchParameters As New Dictionary
SearchParameters.Add "query", "(full_text_myntra:(_)AND(statusid:1008))"
SearchParameters.Add "start", 0
SearchParameters.Add "rows", 500
SearchParameters.Add "facet", True
SearchParameters.Add "facetField", Array()

Set Response = MyntraClient.PostJSON("searchws/search/styleids2", Array(SearchParameters))

' Check status, received content, or do something with the data directly
Debug.Print Response.StatusCode
Debug.Print Response.Content
Debug.Print Response.Data("response1")("totalProductsCount")

关于javascript - 使用 VBA 的 XHR 请求和 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23663149/

相关文章:

javascript - 使用 React 将索引作为状态传递给组件

vba - 如何移动对话中的所有消息?

vba - 电子邮件宏每 40 - 50 封电子邮件暂停一次

ios - 如何在 Swift 中将所有键和值从 NSDictionary 中获取到单独的字符串数组中?

excel - 在 PowerPoint 中查找文本并替换为 Excel 单元格中的文本

javascript - 如何在不立即重置的情况下向 Javascript 中的表添加一行?

javascript - onError 事件未按预期运行

javascript - 使用提交按钮发送而不是回车键

JavaScript XHR - "responseType"属性与 "Content-Type" header

Android,解析 422 响应返回的 json 时出现问题