【问题标题】:Search a webpage and click on a button搜索网页并单击按钮
【发布时间】:2019-08-06 14:59:38
【问题描述】:

我正在尝试在网页上使用 VBA。我想出了如何登录并提交我的用户名和密码。

我需要点击 3 个按钮。一旦单击了上一个按钮,它们就会出现。我有我的 if 语句,如果我逐段浏览代码,它确实有效。

它看起来好像在每个语句中循环了好几次。它经过 if then 部分,然后退出 for、end if、next 并返回 if 语句而不完成任务。它会这样做几次,直到最终成功。

我已经尝试过.document.getElementsbyId,但所有与之相关的都不起作用。

也许有办法搜索文档并让它点击按钮?

它似乎不起作用,因为直到最终它才正确?

'Enters username and password & submits

With .document.forms("signinginn")
    .User.Value = "username"
    .Password.Value = "password"
    .document.forms(0).submit
End With

Application.Wait DateAdd("s", 2, Now)

With IE.document
    Set a = .getElementsbyTagName("input") 

    For Each a In .getElementsbyTagName("input")

        If a.getAttribute("value") = "Start" Then
            a.Click
            Exit For
        End If

    Next a

如果我部分地播放这段代码,它可以工作,但它会经历几次。

我能在第一时间做对吗?此代码的预期输出是立即单击按钮。

【问题讨论】:

    标签: html excel vba


    【解决方案1】:

    尝试为元素的存在添加一个定时循环,适当的页面加载等待,并使用 querySelector 删除当前循环并简单地定位输入元素的属性值

    Option Explicit
    
    'VBE > Tools > References: Microsoft Internet Controls
    Public Sub ClickElement()
        Dim ie As Object, elems As Object, t As Date
        Const MAX_WAIT_SEC As Long = 10
    
        Set ie = CreateObject("InternetExplorer.Application")
        With ie
            .Visible = True
            .Navigate2 "url"
    
            While .Busy Or .readyState < 4: DoEvents: Wend
    
            With .document.forms("signinginn")
                .User.Value = "username"
                .Password.Value = "password"
                .document.forms(0).submit
            End With
    
            While .Busy Or .readyState < 4: DoEvents: Wend
            t = Timer
            Do
                On Error Resume Next
                Set elems = .document.querySelectorAll("input[value=Start]")
                On Error GoTo 0
                If Timer - t > MAX_WAIT_SEC Then Exit Do
            Loop While elems Is Nothing
            If Not elems Is Nothing Then
                elems.item(0).Click
            Else
                Exit Sub
            End If
            'Other code
            Stop   '<=Delete me later
            .Quit
        End With
    End Sub
    

    【讨论】:

    • 在 t= Timer 之前的 While .Busy 行上显示错误 438(对象不支持此属性或方法)
    • 另外,我注释掉了该行以查看问题,但我仍然会遇到同样的问题,它一遍又一遍地循环
    • 好的,我的旧代码可以工作,如果我一块一块地做,但是如果我按继续,你的代码就可以工作
    • 这是Internet Explorer的方法,所以不应该抱怨。您刚刚添加了您的网址吗?
    • 是的,停止命令有效。但是,如果我单独循环通过程序,它会循环并循环直到它工作。如果我只是按播放-程序可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    相关资源
    最近更新 更多