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

mm9b1k5b  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(325)

我尝试通过XMLHTTP对象发送表单数据以获取网页。
我使用的是Excel 2010。
网站名称为http://espn.go.com/mlb/players
我试图通过搜索框搜索某个球员(如费斯特)。
下面是表单标记之间的源代码。

<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
bzzcjhmw

bzzcjhmw1#

这段代码对我很有效:

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-- msxml6.dll位于本机system32文件夹中)
如上所述,表单使用GET请求,因此您可以使用ACTION属性并将INPUT标记的值附加到单个字符串中,如下所示:
http://search.espn.go.com/results?searchString=Fister&page=null&fromForm=true
我对Sub进行了函数化,这样你就可以用不同的玩家名调用它来抓取每一页。当然,如果你希望用有空格的玩家名调用它(here's one),你就需要一个urlencode函数。

sbtkgmzw

sbtkgmzw2#

如果我没有遗漏任何内容,则单击Search按钮后,URL将显示如下:http://www.espn.com/mlb/players?search=Fister

它是GET请求,并且它返回HTML,然后可以例如使用MSHTMLDocument的标准搜索函数来搜索HTML,例如:

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并选择网络流量等。*

相关问题