我正在尝试从电子商务时尚网站获取一些数据。当我在网站上打开一个类别时,我可以看到 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/