【问题标题】:Using VBA and Internet Explorer to Parse HTML使用 VBA 和 Internet Explorer 解析 HTML
【发布时间】:2016-07-14 19:39:32
【问题描述】:

我正在尝试使用 VBA 代码单击网站上的“开始”按钮。这是源代码。

 <div class="actions"> 
  <a id="go" href="javascript:void(null);" title="Go"><img src="/images/button-go-smaller.png"></a>
   <a id="reset" href="javascript:void(null);" title="Reset All Fields"><img src="/images/button-reset_all.png"></a>
                    </div>

这是我的 VBA 代码:

For Each obj In objCollection
     If objCollection(i).ID = "go" Then
        Set objElement = obj
Exit For
    End If
Next obj
objElement.Click

但是,在 objElement.Click 行上,我收到错误 91,这意味着找不到“go”操作。为什么会这样,我如何访问“开始”按钮?

【问题讨论】:

  • 当您已经使用obj 变量循环访问对象集合时,为什么还要使用对象集合索引?此外,您不会在每个循环中增加 i

标签: html vba excel internet-explorer


【解决方案1】:

怎么样……

Dim objCollection As Object
Set objCollection = IE.Document.getElementsbyTagName("a")

For Each obj In objCollection
    If obj.ID = "go" Then
        obj.Click
        Exit For
    End If
Next obj

【讨论】:

    【解决方案2】:

    如果您有一个带有Id 的 html 对象,您可以通过以下方式直接获取它:

    Dim GoObj As Object
    Set GoObj = IE.Document.getElementbyId("go")
    'Only if it was found you click it
    If not GoObj is Nothing then
        GoObj.Click
    End If
    

    注意getElementbyId中的元素与getElementsByTagName中的元素s的区别

    【讨论】:

      【解决方案3】:

      这是一个很好的例子来说明如何做到这一点。

      Dim HTMLDoc As HTMLDocument
      Dim oBrowser As InternetExplorer
      Sub Login_2_Website()
      
      Dim oHTML_Element As IHTMLElement
      Dim sURL As String
      
      On Error GoTo Err_Clear
      sURL = "https://www.google.com/accounts/Login"
      Set oBrowser = New InternetExplorer
      oBrowser.Silent = True
      oBrowser.timeout = 60
      oBrowser.navigate sURL
      oBrowser.Visible = True
      
      Do
      ' Wait till the Browser is loaded
      Loop Until oBrowser.readyState = READYSTATE_COMPLETE
      
      Set HTMLDoc = oBrowser.Document
      
      HTMLDoc.all.Email.Value = "sample@vbadud.com"
      HTMLDoc.all.passwd.Value = "*****"
      
      For Each oHTML_Element In HTMLDoc.getElementsByTagName("input")
      If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
      Next
      
      ' oBrowser.Refresh ' Refresh If Needed
      Err_Clear:
      If Err <> 0 Then
      Debug.Assert Err = 0
      Err.Clear
      Resume Next
      End If
      End Sub
      

      阅读更多:http://vbadud.blogspot.com/2009/08/how-to-login-to-website-using-vba.html#XwwFWylLQi9rjILC.99

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-11
        • 2012-12-10
        • 1970-01-01
        • 2018-05-15
        • 1970-01-01
        • 2020-01-26
        • 1970-01-01
        相关资源
        最近更新 更多