八、更加深入的例子
同12章中通过 HtmlElement类 或者其他方法获取网页上元素信息,
我们也可以通过获得 mshtml.IHTMLDocument2 来获得IE窗口网页元素信息。
这里偷个懒,主要代码同上一小节 vb.net 教程 20-3 控制Ie浏览器 8
但是将ListIe设置为窗体级变量:
Dim listIe As ArrayList
对应列表按钮代码:
Private Sub cbListIE_Click(sender As Object,e As EventArgs) Handles cbListIE.Click listIe = New ArrayList listIe = getIhtmlDoc() If listIe.Count > 0 Then For i As Integer = 0 To listIe.Count - 1 Dim subList As New ListViewItem() subList.Text = i.ToString Dim iedocInfo As New IeDocStructure iedocInfo = CType(listIe.Item(i),IeDocStructure) subList.SubItems.Add(iedocInfo.title) subList.SubItems.Add(iedocInfo.url) lvListIE.Items.Add(subList) Next End If End Sub
所举例子采用的是 http://www.qqrec.com/vblessons/vbnet20-2-1.htm
获得文本框内的信息代码如下:
Private Sub btnInfo_Click(sender As Object,e As EventArgs) Handles btnInfo.Click If lvListIE.SelectedIndices.Count < 1 Then MessageBox.Show("尚未选择一行数据") Exit Sub End If Dim selectedIndex As Integer selectedIndex = lvListIE.SelectedIndices.Item(0) Dim ieInfo As IeDocStructure Dim ie_SHwnd As Integer ieInfo = CType(listIe.Item(selectedIndex),IeDocStructure) ie_SHwnd = ieInfo.IE_SHwnd '获得IHTMLDocument2接口 Dim IEdoc As mshtml.IHTMLDocument2 IEdoc = getDocumentfromIES(ie_SHwnd) Dim studentname As String = "" Dim studentage As String = "" Dim ieElement As mshtml.IHTMLElement For Each ieElement In IEdoc.all Select Case ieElement.id Case "studentname" studentname = ieElement.getAttribute("value") Case "studentage" studentage = ieElement.getAttribute("value") End Select Next MessageBox.Show("学生名称:" & studentname & vbCrLf & "学生年龄:" & studentage) End Sub
运行结果如下图(注意,笔者偷懒直接选择正确的网页,如果选择别的网页不能返回结果的)
不管Ie窗体是被遮挡或者最小化,都会获得正确的结果。
当然请注意:切勿用于做坏事
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net 教程 目录
原文链接:https://www.f2er.com/vb/256390.html