在VBA脚本中使用MSXML提取网站数据

时间:2018-11-20 09:00:26

标签: excel vba excel-vba msxml

我有来自http://dailydoseofexcel.com/archives/2011/03/08/get-data-from-website-that-requires-a-login/#comment-60553

的以下代码
Sub GetTable()
Dim xml As Object ' MSXML2.XMLHTTP60
Dim htmlDoc As Object ' MSHTML.HTMLDocument
Dim htmlBody As Object ' MSHTML.HTMLBody
Dim ieTable As Object
Dim clip As DataObject

Set xml = GetMSXML

With xml
      .Open "POST", "https://web.site", False
      .send "username=myname&password=mypassword"""
End With
With xml
      .Open "POST", "https://web.site/anotherpage", False
End With
Set htmlDoc = CreateHTMLDoc
Set htmlBody = htmlDoc.Body
htmlBody.innerHTML = xml.responseText

Set ieTable = htmlBody.all.Item("report")

    'copy the tables html to the clipboard and paste to teh sheet
  If Not ieTable Is Nothing Then
        Set clip = New DataObject
        clip.SetText "<html>" & ieTable.outerHTML & "</html>"
        clip.PutInClipboard
        Range("A1").Select
        ActiveSheet.PasteSpecial "Unicode Text"""
    End If

End Sub

Function CreateHTMLDoc() As Object ' MSHTML.HTMLDocument
Set CreateHTMLDoc = CreateObject("htmlfile")
End Function

Function GetMSXML() As Object ' MSXML2.XMLHTTP
On Error Resume Next
  Set GetMSXML = CreateObject("MSXML2.XMLHTTP")
End Function

使用此代码,我尝试访问网站web.site并向其传递用户名和密码进行登录,然后再继续浏览该网站的另一页,然后将表的内容(结果)复制到excel的sheet1中工作簿。

我尝试使用f8进行调试,但是没有视觉浏览器,如果我按照此页面http://dailydoseofexcel.com/archives/2011/03/08/get-data-from-website-that-requires-a-login/运行,我会得到 那么很难确切地了解正在发生的事情以及失败的地方。

1 个答案:

答案 0 :(得分:0)

请尝试使用以下代码来帮助您访问网站,如果您有任何疑问,请在我的频道https://www.youtube.com/watch?v=hfAhmae4iqA上发表评论;

Dim IEe As InternetExplorer
    Dim doc, element
    Set IEe = New InternetExplorer

    IEe.Visible = False 'make true if you want to the internet explorer 
    IEe.Navigate "YOUR WEBSITE"

       Do While IEe.ReadyState = 4: DoEvents: Loop
    Do Until IEe.ReadyState = 4: DoEvents: Loop

Set element = IEe.Document.getElementByID(INSERT ELEMENT ID) 'RIGHT CLICK ON WEBSITE AND SAY INSPECT ELEMENT CLICK THE MOUSE ICON AND THEN CLICK THE TEXT BOX WHERE THE PASSWORD OR USERNAME SHOULD BE INSERTED 

element.Value = "USERNAME"

Set element = IEe.Document.getElementByID(INSERT ELEMENT ID) 'THE FIRST IS FOR USERNAME THE NEXT FOR PASSWORD 

element.Value = "PASSWORD" 'remember storing a password in a macro is not safe