首页 > 解决方案 > 在登录页面将数据输入到 div

问题描述

https://imgur.com/a/QauSk1H

Set IE = New InternetExplorer

IE.Visible = True
IE.navigate "https://mdemo.cqg.com/cqg/desktop/logon"
Do While IE.Busy = True: DoEvents: Loop


Set HTMLDoc = IE.document
Set wpfe = HTMLDoc.getElementsByClassName("wpfe-logon-input-full wpfe-native-faded-input ng-untouched ng-pristine ng-valid")(0)
wpfe.Value = "User Login"

我很想输入登录名,但它看起来像 emm... 没什么好。顶部附有有趣代码部分和错误的屏幕。我希望你能提供帮助。

标签: excelvba

解决方案


您想通过 css 类名称获取第一个输入字段"wpfe-logon-input-full wpfe-native-faded-input ng-untouched ng-pristine ng-valid"。我写了名字,因为每个由空格分隔的字符串都是一个自己的 css 类名。最后一个css类名不是ng-valid你加载页面的时候。是ng-invalid。这就是你错误的原因。

解决方案是仅使用第一个 css 类wpfe-logon-input-full。但这还不足以实现您的目标。

在加载第一个 html 代码并且 IE 报告浏览器不再繁忙后,IE 对您撒谎;-) 之后将加载动态内容。所以你必须等到它完成。

但即便如此,登录仍然无法正常工作。您必须为每个输入字段触发两个 html 事件。

此代码有效:

Sub Login()

  Const url As String = "https://mdemo.cqg.com/cqg/desktop/logon"
  
  Dim ie As Object
  Dim HTMLDoc As Object
  Dim nodeUsername As Object
  Dim nodePassword As Object
  
  Set ie = CreateObject("InternetExplorer.Application")
  ie.Visible = True
  ie.navigate url
  Do While ie.Busy = True: DoEvents: Loop
  Application.Wait (Now + TimeSerial(0, 0, 5))
  
  Set HTMLDoc = ie.document
  
  Set nodeUsername = HTMLDoc.getElementsByClassName("wpfe-logon-input-full")(0)
  Call TriggerEvent(HTMLDoc, nodeUsername, "compositionstart")
  nodeUsername.Value = "TestName"
  Call TriggerEvent(HTMLDoc, nodeUsername, "compositionend")
  
  Set nodePassword = HTMLDoc.getElementsByClassName("wpfe-logon-input-full")(1)
  Call TriggerEvent(HTMLDoc, nodePassword, "compositionstart")
  nodePassword.Value = "TestPassword"
  Call TriggerEvent(HTMLDoc, nodePassword, "compositionend")
  
  HTMLDoc.getElementByID("login").Click
End Sub

使用此过程触发 html 事件:

Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)

  Dim theEvent As Object

  htmlElementWithEvent.Focus
  Set theEvent = htmlDocument.createEvent("HTMLEvents")
  theEvent.initEvent eventType, True, False
  htmlElementWithEvent.dispatchEvent theEvent
End Sub

推荐阅读