您可以循环浏览所有输入标签并通过检查“最具识别性”的属性(id、名称、类型、innerHTML 等)来识别相关的标签。这是我在 Excel 工作表中使用的 Sub(),它会自动登录到网站
Sub FormAction(Doc As MSHTML.HTMLDocument, ByVal Tag As String, ByVal Attrib As String, ByVal Match As String, ByVal Action As String)
Dim ECol As MSHTML.IHTMLElementCollection
Dim IFld As MSHTML.IHTMLElement
Dim Tmp As String
Set ECol = Doc.getElementsByTagName(Tag)
For Each IFld In ECol ' cycle thru all <[tag]> elements
If VarType(IFld.getAttribute(Attrib)) <> vbNull Then ' does it contain the attribute
If Left(IFld.getAttribute(Attrib), Len(Match)) = Match Then
If Action = "/C/" Then
IFld.Click
Else
IFld.setAttribute "value", Action
End If
Exit Sub
End If
End If
Next
End Sub
该函数采用以下参数:
- Doc .... HTML DOM 对象
- Tag .... 你想要处理的标签(通常是 input、image、a、...)
- Attrib .... 要匹配其值的属性
- Match .... 属性的匹配值
- Action ..... 如果 "/C/" 对匹配的标签执行 .Click() 动作,否则将动作值放入标签的 value 属性中
如果您想挂钩任何包含 JavaScript 代码的属性(例如“onclick”),请不要忘记您在 HTML 源代码中看到的代码已嵌入到匿名函数中,例如
function anonymous()
{
onclick="exportData(workOrderSearchForm)";
}
如果您想挂钩例如 "exportData(workOrder" ,则需要使用 Instr() 函数或类似函数来考虑这一点。
同样非常重要的是:为页面导航和加载 DOM 对象留出足够的时间。我注意到在我的公司,一旦页面更改,加载时间有时会急剧增加。
我在这方面取得了很好的成功:
Sub MyMainSub()
Dim Browser As SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
' my other Dim's
' start browser
Set Browser = New SHDocVw.InternetExplorer
Browser.navigate "http://www.whatever.com"
WaitForBrowser Browser, 5 ' wait for browser, but not more than 5 sec
' gain control over DOM object
Set HTMLDoc = Browser.document
WaitForBrowser Browser, 5 ' wait for browser, but not more than 5 sec
' do actions
' FormAction HTMLDoc, w, x, y, z
End Sub
Sub WaitForBrowser(Browser As SHDocVw.InternetExplorer, Optional TimeOut As Single = 10)
Dim MyTime As Single
MyTime = Timer ' seconds since midnight
Do While Browser.Busy Or (Timer <= MyTime + TimeOut)
DoEvents ' go do something else
Loop
If Browser.Busy Then
MsgBox "I waited for " & Timer - MyTime & " seconds, but browser still busy" & vbCrLf & _
"exititing Login sequence now"
End
End If
End Sub
希望这足以启发您创建解决方案。
祝你好运迈克