你可以循环遍历所有输入标签,并通过检查“最具标识性”的属性(id、name、type、innerHTML等)来确定相关标签。以下是我在Excel表格中使用的一个子程序,它可以自动登录到网站。
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
希望这足够激励你去创造自己的解决方案。
祝好,MikeD。
<input onclick="toggleCheck();" type="checkbox">
。 - cyberponk