如何使用VBA将文本输入Google并单击搜索

问题描述 投票:3回答:2

我的最终目标是自动使用VBA打开浏览器,输入网站的用户名和密码,然后单击登录以进一步导航到不同的页面并下载文件!

我想从最简单的试用开始,进行谷歌搜索!我认为这个想法是相似的,因为它们都需要输入内容并点击某些东西。

我在IE中找到了 - >工具(Alt + X) - > F12开发者工具可以显示网站的html代码,而且更方便,看来我可以选择区域并获得我感兴趣的关键字!这里是这些地区的两个截图,the first one is for the search bar,我找到了"input name = "q"and the second one is for the search button,在那里我找到了"input name = "btnK"

这是我的代码:

Sub test()

Set IE = CreateObject("InternetExplorer.Application")
my_url = "https://www.google.ca/?gws_rd=ssl"
IE.Visible = True
IE.navigate my_url

'For example, if I want to search "123"
IE.Document.getElementById("q").Value = "123"

'Click the "Search" button
IE.Document.getElementById("btnK").Click


End Sub

它在IE.Document.getElementById("q").Value = "123"返回错误,

对象'iwebbrowser2'的方法'Document'失败。

不明白哪里出错了。我是如何使用VBA来控制浏览器的新手...请帮助,谢谢大家!

vba internet-explorer browser login web
2个回答
1
投票

确保使用正确的等待语法,以便加载页面。您也无需循环提交表单。只需直接提交

.forms(0).submit

码:

Option Explicit
Public Sub test()
    Const MY_URL = "https://www.google.ca/?gws_rd=ssl"
    With CreateObject("InternetExplorer.Application")
        .Visible = True
        .navigate MY_URL
        While .Busy Or .readyState < 4: DoEvents: Wend

        With .document
            .getElementById("lst-ib").Value = "123"
            .forms(0).submit
        End With
        'Other code
        '.Quit  '<== Uncomment me later
    End With
End Sub

1
投票

HTML元素的名称与ID不同。

例如,"q"不是搜索栏的ID,而是名称。它的ID是"lst-ib"

添加代码:

Sub test()

    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    my_url = "https://www.google.ca/?gws_rd=ssl"
    ie.Visible = True
    ie.navigate my_url

    Do While ie.Busy
        DoEvents
    Loop
    Wait 3

    'For example, if I want to search "123"
    ie.Document.getElementById("lst-ib").Value = "123"

    ' Pressing enter
    SendKeys "{ENTER}"

End Sub

Sub Wait(seconds As Integer)

    Application.Wait Now + timeValue("00:00:0" & CStr(seconds))

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.