打开网页,然后单击特定选项卡

时间:2013-07-13 19:15:43

标签: excel vba

我正在尝试按下按钮打开网页,转到特定部分,在下一个按钮箭头图像点击时遍历多个页面。

我必须从这个网站提取信息。页面的HTML结构是:

<div>
 <div>
  <table class="A">
   <tbody>
    <tr>
     <td class="B">
      <div class="C">
       <ul id="D" class="E">
        <li id="W" class="T U"></li>
        <li id="X" class="T U "></li>
        <li id="Y" class="T U"><span class="SPANCLASSNAME">HEADER TAB CAPTION</span></li>
        <li id="Z" class="T U"></li>
       </ul>
      </div>
     </td>
    </tr>
   </tbody>
  </table>  
 </div>
</div>

我需要的所有数据都可以在任何li元素下。在这里,我将它放在第三个li元素下。

Private Sub Button_Click()
    Dim IE As Object    
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.Navigate "URL"

    Do
        DoEvents
    Loop Until IE.ReadyState = 4

    Set AllSpanElements = IE.Document.getElementsByClassName("SPANCLASSNAME")
    For Each span In AllSpanElements
        MsgBox span.innerText
        If span.innerText = "HEADER TAB CAPTION" Then
            MsgBox span.innerText
                span.Click  'DOES NOT WORK. WHAT SHOULD BE THE CODE HERE?
            Exit For
        End If
    Next    
    MsgBox "Operation Completed"
End Sub

我可以打开网页,MsgBox显示所有li元素的文本,并且流程到达操作已完成,但点击操作不会发生。

什么代码会将点击操作发送到IE?

3 个答案:

答案 0 :(得分:0)

如果跨度附加了javascript事件,则下面的代码可能会有效。

 span.FireEvent("click()")

答案 1 :(得分:0)

我相信会是

span.onclick();
// or
span.fireEvent('onclick');

(没有分号)

已添加如果它不是JS附加事件,请尝试

span.click()

答案 2 :(得分:0)

我无法在不知道网址的情况下对其进行测试,但下面是我提出的代码:

Public Sub sampleCode()
Dim IE As InternetExplorer
Dim HTMLDoc As HTMLDocument
Dim AllSpanElements As IHTMLElementCollection
Dim spanCounter As Long
Dim targetSpan As HTMLObjectElement

Set IE = New InternetExplorer
With IE
    .Visible = True
    .Navigate "URL"
    Do While .Busy Or .ReadyState = READYSTATE_LOADING: Wend
    Set HTMLDoc = .document
End With

Set AllSpanElements = HTMLDoc.getElementsByTagName("li")
For spanCounter = 0 To AllSpanElements.Length - 1
    With AllSpanElements(spanCounter)
        MsgBox (.innerText)
        If .innerText = "HEADER TAB CAPTION" Then
            MsgBox (.innerText)
            .Click
            Exit For
        End If
    End With
Next

IE.Quit
Set IE = Nothing
MsgBox "Operation Completed"

End Sub

希望这有帮助, TheSilkCode