【100分求教】Webbrowser赋值3层框架出错,两层通过,求达人分析代码
测试软件:VB 6.0
测试环境:win7
把测试1.html、测试2.html放在D盘,执行VB脚本的时候如果Webbrowser1.Navigate "D:\测试1.html",就能赋值,Webbrowser1.Navigate "D:\测试2.html"就赋值不了了。请大侠们赐教!
测试1.html
<iframe application="yes" width=600 height=600 name = "qwe" id="wori" src="http://www.baidu.com/"></iframe>
<iframe border=0 name=lantk src="D:\测试1.html" width=500 height=400 allowTransparency scrollbars=yes frameBorder="0">
</iframe>
Private IframeIE() As SHDocVw.WebBrowser
Private Sub Command1_Click()
EnumFrames Webbrowser1
MsgBox IframeIE(0).Document.body.innerHTML
IframeIE(0).Document.getElementById("kw").Value = "xxxxxx "
End Sub
Private Sub Form_Load()
Webbrowser1.Navigate "D:\测试2.html"
End Sub
Public Function getObjByAtt(doc, tagName, Att, selfAtt) As Object
Dim doc_1 As Object, i As Object
Set doc_1 = doc.getElementsByTagName(tagName)
For Each i In doc_1
If i.getAttribute(Att) = selfAtt Then
Set getObjByAtt = i
Exit Function
Exit For
End If
Next
Set getObjByAtt = Nothing
End Function
'下面代码的核心是修改自MVP Edanmo的大作
'枚举框架,参数WB是一个webbrowser控件的名称,其中承载着我们要分析的页面
Sub EnumFrames(ByVal WB As WebBrowser)
Dim j As Integer
Dim pContainer As olelib.IOleContainer
Dim pEnumerator As olelib.IEnumUnknown
Dim pUnk As olelib.IUnknown '获得页面的Document接口,然后我们就可以对其为所欲为了
Set pContainer = WB.Object.Document
'很奇怪,有时候上面这段对象赋值出错,用下面这句就没有问题了
'Set pContainer = WB.Document
If pContainer.EnumObjects(OLECONTF_EMBEDDINGS, pEnumerator) = 0 Then
Set pContainer = Nothing
Do While pEnumerator.Next(1, pUnk) = 0
On Error Resume Next
If Err.Number = 0 Then
'将框架页面依次赋值到IframeIE数组中
ReDim Preserve IframeIE(0 To j)
Set IframeIE(j) = pUnk
' Debug.Print IframeIE(j).Document.body.innerhtml
j = j + 1
End If
Loop
Set pEnumerator = Nothing
End If
End Sub
Dim collweb As Collection '专门用来保存上框架的各个WebBrowser对象
Private Sub Command1_Click()
getEleById("kw").Value = "xxxxxx " '即可设置百度查找框的值
End Sub
Private Sub Form_Load()
Webbrowser1.Navigate "D:\测试2.html"
End Sub
Private Sub Webbrowser1_BeforeNavigate2(ByVal pDisp As Object, URL As Variant, Flags As Variant, TargetFrameName As Variant, PostData As Variant, Headers As Variant, Cancel As Boolean)
On Error Resume Next
Dim i As Long, k As Long
'以下程序保存框架对象
If pDisp Is Webbrowser1.object Then
Set collweb = New Collection
collweb.Add pDisp
Else
k = 0
For i = 1 To collweb.Count
If pDisp Is collweb(i) Then
k = i
Exit For
End If
Next
If k > 0 Then collweb.Remove k
collweb.Add pDisp
End If
Debug.Print "共有框架数:"; collweb.Count
End Sub
function getEleById(id) As IHTMLElement '根据id获得元素
On Error Resume Next
Dim i As Integer, ele As IHTMLElement
For i = 1 To collweb.Count
For Each ele In collweb(i).Document.body.All
If InStr(ele.Id, id) Then
getEleById=ele
exit function
End If
Next
Next
End Sub