首页 > 解决方案 > 如何使用 Excel VBA 获取 POST 请求的所有表单数据?

问题描述

我正在尝试使用 Excel VBA 抓取使用 ASP.NET Ajax 开发的网站。我正在使用 Microsoft HTML 对象库和 Microsoft XML,v6.0 库。我想做的是当我在第一个文本框中选择一个项目时,将第二个文本框中的所有项目放入一个表格中。

当您在第一个文本框中选择一个项目时,会自动加载第二个文本框中的项目。所以首先我GET网站发出请求,然后我用类抓取所有元素aspNetHidden。我将两个元素添加到POST第一次抓取中没有出现的字符串中:ctl00$ctl18, __ASYNCPOST, 以及它们各自的值。我还添加了第一个文本框的值ctl00$MainContent$cboDenominacionSocial

Sub Macro1()
'
' Macro1 Macro
'
    ' Declare variables
    Dim xmlhttp As New MSXML2.XMLHTTP60
    Dim urlMF As String

    '
    urlMF = "https://www.smv.gob.pe/Frm_EVCP?data=5A959494701B26421F184C081CACF55BFA328E8EBC"

    '

    '
    xmlhttp.Open "GET", urlMF, False
    'xmlhttp.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3842.0 Safari/537.36"
    'xmlhttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
    xmlhttp.send

    Dim bodySMV As New HTMLDocument
    bodySMV.body.innerHTML = xmlhttp.responseText

    Dim topicsSMV As Object
    Dim topicElem As Object

    Set topicsSMV = bodySMV.getElementsByClassName("aspNetHidden")

    Dim postReq As String
    postReq = ""

    i = 1
    For Each topic In topicsSMV
        Set topicElem = topic.getElementsByTagName("input")
        For Each dataTopic In topicElem
            Cells(i, 1) = dataTopic.Name
            Cells(i, 2) = dataTopic.Value
            temp = dataTopic.Name & "=" & dataTopic.Value
            If i = 1 Then postReq = "ctl00%24ctl18=ctl00%24MainContent%24UpdatePanel1%7Cctl00%24MainContent%24cboDenominacionSocial"
            If i > 1 Then postReq = postReq & Chr(38) & temp
            i = i + 1
        Next dataTopic
    Next topic
    postReq = postReq & "ctl00%24MainContent%24cboDenominacionSocial=156429&__ASYNCPOST=true&"
    Cells(i, 1).Value = postReq

    xmlhttp.Open "POST", urlMF, False
    xmlhttp.send postReq
    bodySMV.body.innerHTML = xmlhttp.responseText

'
End Sub

我想从第二个文本框中获取所有可能元素的列表,具体取决于第一个框的选择。我的POST请求中缺少什么?

标签: excelvbapostweb-scraping

解决方案


推荐阅读