VBA中的HTTP发布请求的空响应

时间:2019-03-26 17:18:12

标签: vba post web-scraping xmlhttprequest winhttprequest

我正在尝试在VBA中发出HTTP发布请求,但响应为空。 这是我的代码:

Sub User()
    On Error Resume Next
    Dim HTTPreq As WinHttpRequest
    Set HTTPreq = New WinHttpRequest
    URL = "https://www.transfermarkt.com/site/DropDownWettbewerbe"
    HTTPreq.Open "POST", URL, False
    HTTPreq.setRequestHeader "user-agent", "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/7.0.185.1002 Safari/537.36"
    HTTPreq.send "land_id=189"
    MsgBox (HTTPreq.responseText)
End Sub

我在Python中做过同样的事情,并得到了预期的响应:

<pre><option value="">Competition</option><option value="GB1">Premier League</option><option value="GB2">Championship</option><option value="GB3">League One</option><option value="GB4">League Two</option><option value="CNAT">National League</option><option value="GB21">Premier League 2</option><option value="GB18">U18 Premier League</option><option value="GBFL">EFL Trophy</option><option value="FAC">FA Cup</option><option value="CGB">EFL Cup</option><option value="GBCS">Community Shield</option><option value="FAYC">FA Youth Cup</option>.

不确定在VBA中我在哪里做错了

1 个答案:

答案 0 :(得分:0)

您需要指定content-type标头,以下代码对我来说效果很好:

Sub User()

    With CreateObject("WinHttp.WinHttpRequest.5.1")
        .Open "POST", "https://www.transfermarkt.com/site/DropDownWettbewerbe", False
        .SetRequestHeader "content-type", "application/x-www-form-urlencoded; charset=UTF-8"
        .SetRequestHeader "user-agent", "user-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64)"
        .Send "land_id=3"
        MsgBox .ResponseText
    End With

End Sub

您可以从浏览器开发人员工具的“网络”标签中找到必要的标题:

developer tools network tab