如何在MSXML2.xmlhttp的POST请求中正确传递参数?
使用MSXML2.xmlhttp发送POST请求未得到预期结果的问题
我不清楚如何用MSXML2.xmlhttp向网站发送带特定参数的请求。评论区的SSlinky指出我的尝试技术上没问题,所以我展示一个更贴切的示例:
剑桥词典翻译请求示例
我成功获取了剑桥词典翻译页面的首页内容:
myURL = "https://dictionary.cambridge.org/it/translate/" xmlhttp.Open "GET", myURL, False xmlhttp.send html.body.innerHTML = xmlhttp.responseText Set form = html.getElementsByClassName("clrd nocontain")(0) action = "https://dictionary.cambridge.org/it/translate/"
随后收集所有隐藏输入项:
Set inputList = form.getElementsByTagName("input") For Each hiddenInput In inputList If InStr(hiddenInput.outerHTML, "hidden") Then If querystring = "" Then querystring = hiddenInput.getAttribute("name") & "=" & hiddenInput.getAttribute("value") Else querystring = querystring & "&" & hiddenInput.getAttribute("name") & "=" & hiddenInput.getAttribute("value") End If End If Next
接着添加指定输入值并调用POST请求:
body = "txtTrans=dog&" & querystring Call xmlhttp.Open("POST", action, False) Call xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") Call xmlhttp.send(body) If xmlhttp.Status <> 200 Then Exit Sub html.body.innerHTML = xmlhttp.responseText
预期结果:在responseText中得到包含翻译结果的元素:
<div id="translate-tool__result" class="tc-bb translate-tool__result translate-english-spanish js-translator-result" lang="it"> cane </div>
实际结果:返回的元素为空,没有翻译内容:
<div class="tc-bb translate-tool__result translate-english-spanish js-translator-result" id="translate-tool__result"> </div>
WordReference翻译请求示例
我之前用以下示例模拟问题,将输入项si的值设为dog,action从form中获取:
页面中的输入元素:
<input type="text" name="w" id="si" oninvalid="alert('Caratteri non validi nella casella di ricerca');" pattern="^[^<>%\\]*$" size="20" maxlength="200" tabindex="1" onkeydown="keyDown(event)" accesskey="s" title="accesskey: s" value="" placeholder="" autocomplete="off" autocorrect="off" autocapitalize="none">
我的请求代码:
Dim xmlhttp As New MSXML2.xmlhttp Dim html As New HTMLDocument Dim action As String Dim body As Variant action = "https://www.wordreference.com/redirect/translation.aspx" body = "si=dog" Call xmlhttp.Open("POST", action, False) Call xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") Call xmlhttp.send(body) If xmlhttp.Status <> 200 Then Exit Sub html.body.innerHTML = xmlhttp.responseText Debug.Print html.getElementsByClassName("ToWrd").Length
手动网页交互时能正常获取包含结果的<TD>元素(类名为ToWrd),但代码请求的响应中始终找不到该元素,Length值为0。
请问我遗漏了什么?
内容的提问来源于stack exchange,提问作者Claudio
相关产品推荐
相关产品推荐

