【问题标题】:Unable to click on "Documents" tab from <div class = "TabContent TitleTabContainer"> through vba code无法通过 vba 代码从 <div class = "TabContent TitleTabContainer"> 中单击“文档”选项卡
【发布时间】:2019-02-26 20:23:58
【问题描述】:
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

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

【问题讨论】:

  • 如果你在attr.Click这一行设置断点,你打到了吗?
  • 不要通过标签名称“a”获取所有元素,而是尝试使用 CSS 选择器 a[title='Documents']。这应该会让你得到你需要的,没有循环然后点击它
  • @matteo NNZ - 在断点模式下是的,当我调试它达到 attr.Click 但初始化为空值
  • @JeffC - 感谢您的快速建议,我今天一定会尝试使用 CSS 选择器。

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


【解决方案1】:

我尝试测试您的代码,它在 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 中的输出:

此外,您可以尝试参考代码并尝试根据您的要求对其进行修改。

【讨论】:

    【解决方案2】:

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

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

    您还可以在类中添加:

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

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

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

    【讨论】:

    • 以上有没有成功?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多