使用getElementsByClassName的Excel VBA HTML自动化有时会起作用,有时候也不会

时间:2018-02-14 14:05:45

标签: html excel vba excel-vba internet-explorer

我已经创建了一个打开Internet Explorer的宏,导航到带有文章列表的特定网页(每篇文章都有相同的类,但不同的文本),然后单击特定的文章。到目前为止,一切都运行良好(下面的代码中的第1部分)。但是,当我尝试再次执行完全相同的操作(但具有不同的类和innertext)时(下面的代码中的第2部分),它可以随机地工作或不完全(如我所见)。也许有人能给我一个线索,每次都可以让它顺利运行?

此外,当我按步骤(F8)运行时,它总是有效。

HTML代码 第1部分:

 <div class="article-title">Some text in russian</div>

第2部分:

 <a href="javascript:void(0);" class="js-popup-open" data-
 popup="callback">Some text in russian 2</a>

这是我到目前为止所做的:

Private Declare PtrSafe Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds 
As Long)
Private Declare PtrSafe Function ShowWindow Lib "user32" (ByVal hwnd As 
Long, ByVal nCmdShow As Long) As Long
Private Const SW_SHOWMAXIMIZED = 3

Sub sup()

Dim aEle As HTMLLinkElement
Dim aaEle As HTMLLinkElement

Dim objIE As Object

Dim hwnd As Long

Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True


  objIE.navigate "http://www.spark-interfax.ru/ru/services"

ShowWindow objIE.hwnd, SW_SHOWMAXIMIZED
  Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
'Sleep (3000) (tried both variants, doesnt help)

'Part 1

 For Each aEle In objIE.document.getElementsByClassName("article-title")

    Debug.Print aEle.innerText
     On Error Resume Next

    If aEle.innerText = "Some text in russian" Then Exit For
    Next aEle

   aEle.Click

   Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
'  Sleep (3000) (again, tried both)

  'Part 2
   For Each aaEle In objIE.document.getElementsByClassName("js-popup-open")

    Debug.Print aaEle.innerText
     On Error Resume Next

    If aaEle.innerText = "some text in russian 2" Then  Exit For
    Next aaEle
    aaEle.Click

    End Sub

0 个答案:

没有答案