You need to enable JavaScript to run this app. 使用VBA爬取需SendKeys触发密码表单的网站,现有代码运行失败求助
优惠活动
大模型
产品
解决方案
定价
更多

使用VBA爬取需SendKeys触发密码表单的网站,现有代码运行失败求助

代码调整方案

问题原因

你访问的是Angular构建的单页应用,登录表单是页面初始加载完成后异步渲染的,原有代码的固定5秒等待无法保证表单已完成渲染,且直接给input的Value属性赋值不会触发前端框架绑定的输入事件,因此无法唤起密码输入框,也无法触发后续的登录校验逻辑。

调整后完整代码

' 提前在VBA编辑器的工具-引用中勾选:
' 1. Microsoft Internet Controls
' 2. Microsoft HTML Object Library
Sub login()
    Dim IE As InternetExplorer
    Dim idoc As MSHTML.HTMLDocument
    Dim cpfInput As MSHTML.HTMLInputElement
    Dim pwdInput As MSHTML.HTMLInputElement
    Dim submitBtn As MSHTML.HTMLButtonElement
    
    Set IE = New InternetExplorer
    IE.Visible = True
    IE.navigate "https://wsvr10.coamo.com.br/npl/#!/login"
    
    ' 等待初始页面加载完成
    Do While IE.readyState <> READYSTATE_COMPLETE Or IE.Busy
        DoEvents
    Loop
    Set idoc = IE.document
    
    ' 等待CPF输入框渲染完成,最多等10秒
    Set cpfInput = WaitForElement(idoc, "input[id='cpf']", 10)
    If cpfInput Is Nothing Then
        MsgBox "CPF输入框加载超时"
        IE.Quit
        Exit Sub
    End If
    
    ' 输入CPF
    cpfInput.Value = "11111111111"
    ' 触发输入事件,唤起密码框
    cpfInput.FireEvent "oninput"
    cpfInput.FireEvent "onchange"
    
    ' 等待密码输入框渲染完成
    Set pwdInput = WaitForElement(idoc, "input[type='password']", 5)
    If pwdInput Is Nothing Then
        MsgBox "密码输入框加载超时"
        IE.Quit
        Exit Sub
    End If
    
    ' 输入密码
    pwdInput.Value = "你的登录密码"
    ' 触发密码输入事件
    pwdInput.FireEvent "oninput"
    pwdInput.FireEvent "onchange"
    
    ' 点击登录按钮,可按实际元素属性调整选择器
    Set submitBtn = idoc.querySelector("button[type='submit']")
    If Not submitBtn Is Nothing Then
        submitBtn.Click
    End If
    
    ' 后续爬取逻辑可在此补充
End Sub

' 自定义等待元素加载函数
Function WaitForElement(doc As MSHTML.HTMLDocument, selector As String, timeout As Integer) As MSHTML.HTMLElement
    Dim endTime As Double
    endTime = Timer + timeout
    Do While Timer < endTime
        On Error Resume Next
        Set WaitForElement = doc.querySelector(selector)
        On Error GoTo 0
        If Not WaitForElement Is Nothing Then Exit Function
        DoEvents
    Loop
    Set WaitForElement = Nothing
End Function

注意事项

如果元素选择器匹配不到,可以打开IE的F12开发者工具,手动选中对应元素查看实际的id、name、类名,调整querySelector的参数即可。如果触发事件后密码框还是没有弹出,可以额外添加一行cpfInput.focus先聚焦输入框再赋值,确保事件能被正确捕获。

内容的提问来源于stack exchange,提问作者Luís Guilherme Bueno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 09:36:05