使用VBA

时间:2015-08-23 15:31:21

标签: excel vba excel-vba internet-explorer web-scraping

我正在尝试通过VBA脚本自动执行我的日常任务,自动登录到我的银行帐户并从网站返回一些数据。但是,我无法编写可以登录此网站的宏 - https://online.mbank.pl/pl/Login

我写了以下宏,它适用于“普通”网站,例如google(基于输入框ID),但不适用于银行网站返回,出现以下错误:

  

运行时错误424:需要对象

enter image description here

google.com的代码:

Sub LoginHttps()

    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")

    With IE
        .Top = 0
        .Left = 0
        .Height = 1000
        .Width = 1250
        .Visible = True
        .Navigate "https://www.google.com/?gfe_rd=cr&ei=N-TZVaPMAdCv8wf19aH4Bw&gws_rd=cr&fg=1"

        Do While .Busy Or Not .ReadyState = 4: DoEvents: Loop

        .Document.getElementById("lst-ib").Value = "input"
    End With
End Sub

以及生成424错误的银行网站代码:

Sub LoginHttps()

    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")

    With IE
        .Top = 0
        .Left = 0
        .Height = 1000
        .Width = 1250
        .Visible = True
        .Navigate "https://online.mbank.pl/pl/Login"

        Do While .Busy Or Not .ReadyState = 4: DoEvents: Loop

        .Document.getElementById("userID").Value = "input"
    End With
End Sub

我想知道是否有任何方法可以通过VBA访问这些输入框,或者它是由银行程序员保护的。

2 个答案:

答案 0 :(得分:1)

以下是三个顺序检查:第一个Do ... Loop是IE状态的常规检查,第二个 - 文档完整性检查,第三个 - 目标元素检查,当目标节点未准备好时,它返回Null(而不是HTMLInputElement对象的时候。)

Sub LoginHttps()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .Top = 0
        .Left = 0
        .Height = 1000
        .Width = 1250
        .Visible = True
        .Navigate "https://online.mbank.pl/pl/Login"
        Do While .Busy Or .ReadyState < 4: DoEvents: Loop
        Do Until .document.readyState = "complete": DoEvents: Loop
        Do While IsNull(.document.getElementById("userID")): DoEvents: Loop
        .document.getElementById("userID").Value = "input"
    End With
End Sub

答案 1 :(得分:0)

似乎IE在整个页面加载之前返回“就绪”状态。该网站可能正在使用AJAX加载其他内容或进行某种重定向。尝试添加一个小延迟,然后再检查页面是否准备就绪。例如:

.Navigate "https://online.mbank.pl/pl/Login"

' Small delay...
Application.Wait Now + TimeValue("00:00:02")

Do While .Busy Or Not .ReadyState = 4: DoEvents: Loop

.Document.getElementById("userID").Value = "input"

这对我有用。