无法通过VBA代码从<div class =“ TabContent TitleTabContainer”>中单击“文档”选项卡

时间:2019-02-26 20:23:59

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

Private Declare PtrSafe Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdSHow As Long) As Long

Sub Pulldata_BI_Launch()
CreateObject("Shell.Application").Windows
Dim IE As New SHDocVw.InternetExplorer    
Dim htmldoc As MSHTML.HTMLDocument    
Dim elems As MSHTML.IHTMLElementCollection    
Dim attr As MSHTML.IHTMLBodyElement    

'Make internet explorer visible    
IE.Visible = True    
IE.Navigate "https://*************** "    
ShowWindow IE.hwnd, 3

'Wait for page loads fully    
Do While IE.readyState <> READYSTATE_COMPLETE    
Loop

'Collect webpage opened in variable    
Set htmldoc = IE.document

'Click on Documents tab from container    
Set elems = htmldoc.getElementsByTagName("a")    
    Set attr = elems.Item    
    For Each attr In elems    
    If (attr.Item("title") = "Documents") Then    
    attr.Click    
    Exit For    
    End If    
    Next attr    
End Sub

我希望通过代码单击首页标签旁边的文档标签,但无法这样做。任何帮助将不胜感激。以下是“文档”选项卡按钮的检查元素的屏幕截图: enter image description here

2 个答案:

答案 0 :(得分:0)

我尝试测试您的代码,该代码在2个地方出现类型不匹配错误。

我建议您使用下面的代码进行测试,该代码可以单击“文档”选项卡。

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
<script>
function abc()
{
alert("hi....");
}
</script>
</head>
<body>

<div class="TabContent TitleTabContainer">
<a title="Documents" class="TabTitle" role="tab" style="width:auto;" onclick="abc()" href="javascript:void(null);">Documents</a>
</div>

</body>
</html>

VBA代码:

Sub demo()
Dim ie As Object
Dim form As Variant, button As Variant
Set ie = CreateObject("InternetExplorer.Application")


With ie
.Visible = True
.Navigate ("C:\Users\Administrator\Desktop\48.html")

While ie.readyState <> 4
DoEvents
Wend

For Each l In ie.document.getElementsByTagName("a")
    If l.Title = "Documents" Then
        l.Click
        Exit For
        End If

    Next

End With
End Sub

IE 11中的输出:

enter image description here

此外,您可以尝试引用代码并尝试根据需要对其进行修改。

答案 1 :(得分:0)

您可以尝试使用CSS属性=值选择器

ie.document.querySelector("[title=Documents]").click

您还可以添加课程:

ie.document.querySelector(".TabTitle[title=Documents]").click

在点击之前,请确保您有适当的页面加载等待时间:

While ie.Busy Or ie.readyState < 4: DoEvents: Wend