在VBA中通过XMLHTTP发送表单数据

时间:2011-08-08 15:27:56

标签: excel-vba post xmlhttprequest vba excel

我一直在使用Excel 2010.我正在尝试通过XMLHTTP对象发送表单数据以获取没有运气的网页。我正在工作的网站是http://espn.go.com/mlb/players,我正试图通过搜索框(例如Fister)搜索某个玩家。以下是表单标记之间的源代码。

<form id="searchBox" name="searchBox" action="http://search.espn.go.com/results" method="get" accept-charset="utf-8" style="color: #999999;">
<div class="clearfix">
<input autocomplete="off" class="text" type="text" placeholder="Search" name="searchString" id="searchString" />
<input type="hidden" name="page" id="page" value="null" />
<input type="hidden" name="fromForm" value="true" />

<input class="submit" type="submit" value="" />
</div>
</form>

我尝试进行搜索的代码如下所示。

Sub SearchPlayer()
Dim xml As MSXML2.ServerXMLHTTP
Dim search, url As String

search = "searchString=Fister&page=null&fromForm=true"
url = "http://espn.go.com/mlb/players"

Set xml = New MSXML2.ServerXMLHTTP
xml.Open "POST", url, False
xml.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xml.send search

MsgBox xml.responseText

Set xml = Nothing
End Sub

2 个答案:

答案 0 :(得分:0)

此代码对我有用:

Function SearchPlayer(playerName As String) As String

Dim xml As MSXML2.XMLHTTP60
Dim result As String

Const BASE_URL As String = "http://search.espn.go.com/results?searchString={name}&page=null&fromForm=true"

Set xml = CreateObject("MSXML2.XMLHTTP.6.0")

With xml
  .Open "GET", Replace(BASE_URL, "{name}", playerName), False
  .send
End With

result = xml.responseText

SearchPlayer = result

End Function

(假设您的系统上有MSXML 6.0 - 本地system32文件夹中的msxml6.dll)

如上所述,表单使用GET请求,因此您将使用ACTION属性并将INPUT标记的值附加到单个字符串上,如下所示:

http://search.espn.go.com/results?searchString=Fister&page=null&fromForm=true

我对Sub进行了功能化,因此您可以使用不同的播放器名称来调用它来刮取每个页面。当然,如果您希望使用包含空格的播放器名称(here's one)调用它,则需要urlencode函数。

答案 1 :(得分:0)

如果我没有丢失任何东西,则单击URL按钮后的Search如下所示:http://www.espn.com/mlb/players?search=Fister

enter image description here

这是GET请求,它返回HTML,然后可以进行搜索,例如使用MSHTMLDocument的标准搜索功能,例如:

Sub SearchPlayer()
    Dim http As MSXML2.ServerXMLHTTP
    Dim html As MSHTML.HTMLDocument ' Add reference to Microsoft HTML Object Library
    Dim url As String
    Dim player As String

    player = "Fister"
    url = "http://www.espn.com/mlb/players?search=" & player

    Set http = New MSXML2.ServerXMLHTTP
    http.Open "GET", url, False
    http.send

    Set html = New HTMLDocument
    html.body.innerHTML = http.responseText

    Dim nextGamePlace As MSHTML.HTMLDivElement
    Set nextGamePlace = html.querySelector("div[class='game-details'] div[class='venue']")

    Debug.Print nextGamePlace.textContent ' prints Miller Park
End Sub

注意:要观看请求,只需在浏览器中按F12并选择网络流量等。