首页 > 解决方案 > VBA:单击 Internet Explorer 中的“Google 搜索”按钮

问题描述

我正在尝试使用带有 VBA 的 Internet Explorer 修复我的网页抓取地址的代码。最近的更新弄乱了我的代码,我无法找到点击“Google 搜索”按钮的方法。我之前没有遇到过这个问题,因为我的代码之前点击了放大镜图标,但新的更新删除了该图标。

我对 VBA 相当陌生,但我一直在通过尝试使用 IHTMLElementCollection 访问多个类名中的特定元素来搜索互联网以解决该问题,但我仍然无处可去。第一段代码 (elm1) 将地址输入到 google 的搜索栏中。我尝试使用的其余代码访问并单击“Google 搜索”按钮:

Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
URL = "https://www.google.com/"
ie.Navigate URL
Application.StatusBar = URL & " is loading. Please wait..."

'Trying to get google search button for elm2
Dim oHtml As HTMLDocument
Dim oElement As Object
Dim objDS As IHTMLElementCollection
Dim objLSBB As IHTMLElementCollection

Do While ie.ReadyState = 4: DoEvents: Loop
Do Until ie.ReadyState = 4: DoEvents: Loop

Application.StatusBar = URL & " Loaded"


Set elm1 = ie.document.getElementsByName("q")
    For n = 0 To elm1.Length - 1
        If elm1(n).Value = "" Then
            elm1(n).Focus
            elm1(n).Value = endCell.End(xlUp).Offset(1, -1).Value & " Map"
            Exit For
        End If
    Next n

'Set elm2 = ie.document.getElementsByTagName("a")
'elm2.Click
'Set elm2 = ie.document.querySelector("[class='ds']")
'elm2.Click

    
'Set list2 = ie.document.querySelector(".ds")
'Debug.Print list2.Children(0).innerText

'Set objDS = ie.document.getElementsByClassName("ds")
'For i = 0 To objDS.Length - 1
  '  Debug.Print objDS(i).innerHTML
    
'Next





'Set objLSBB = objDS(0).getElementsByClassName("lsbb")
'Debug.Print objLSBB.Children(0).innerText

'Set objDS = ie.document.getElementsByClassName("lsbb")
'For Each elm In objDS
'    Debug.Print elm.innerHTML
    
    
'Next

我已经能够正确访问“Google 搜索”按钮,但由于某种原因,尝试单击该按钮时,.Click 将不起作用。这让我很困惑,因为按钮的 type="submit"。我还发布了来自谷歌的 html 截图作为参考。

谷歌 html

任何帮助,将不胜感激。

标签: vbainternet-explorer

解决方案


您只需使用其名称即可获得“Google 搜索”按钮btnG。你可以参考我下面的示例代码,它运行良好:

Sub LOADIE()
Dim IE As InternetExplorer

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate ("https://www.google.com")

Do Until IE.readyState = 4
   DoEvents
Loop

IE.document.getElementsByName("q")(0).Value = "Map"
IE.document.getElementsByName("btnG")(0).Click

End Sub

结果:

在此处输入图像描述


推荐阅读